Example #1
0
    def getSkinParts(self):
		self.parts = {}
		self.screens = {}
		self.partlist = ConfigSubList()
		self.screenlist = ConfigSubDict()
		self.idx = 0
		self.readSkinParts("/usr/share/enigma2/MetrixHD/skinparts/")
Example #2
0
	def __init__(self, session, action, value, url):
		self.defaultImg = 'Extensions/OnDemand/icons/SHOUTcast.png'

		self.showWMA = str(config.ondemand.ShowiRadioWMA.value)
		self.showDefault = str(config.ondemand.ShowShoutcastDefault.value)
		self.showIcon = str(config.ondemand.ShowShoutcastLogos.value)

		if self.showIcon == 'True':
			if self.showDefault == 'False':
				self.defaultImg = ''

		self.favoriteConfig = Config()
		if os_path.exists(FAVORITE_FILE):
			self.favoriteConfig.loadFromFile(FAVORITE_FILE)

		self.favoriteConfig.entriescount = ConfigInteger(0)
		self.favoriteConfig.Entries = ConfigSubList()
		self.initFavoriteConfig()

		self.screenName = "ShoutStreamsThumbCommon"
		StreamsThumbCommon.__init__(self, session, action, value, url, self.screenName)

		self.skin = """
				<screen position="0,0" size="e,e" flags="wfNoBorder" >
					<widget name="lab1" position="0,0" size="e,e" font="Regular;24" halign="center" valign="center" transparent="0" zPosition="5" />
					<widget source="Title" render="Label" position="20,0" size="e,50" font="Regular;32" />
					<widget name="list" position="0,50" size="e,e-50" scrollbarMode="showOnDemand" transparent="1" />
					<ePixmap pixmap="ViX-Common/buttons/green.png" position="800,10" size="40,40" transparent="1" alphatest="on" />
					<widget source="key_green" render="Label" position="810,0" zPosition="1" size="200,40" font="Regular;20" valign="center" halign="center" transparent="1" />
				</screen>"""

		self["key_green"] = StaticText(_("Add to Favorites"))

		self["genreActions"] = ActionMap(["ColorActions"],
		{
			"red": self.red_pressed,
			"green": self.green_pressed,
			"yellow": self.yellow_pressed,
			"blue": self.blue_pressed,

		}, -1)
Example #3
0
File: Ci.py Project: zukon/enigma2
def InitCiConfig():
	config.ci = ConfigSubList()
	config.cimisc = ConfigSubsection()
	if SystemInfo["CommonInterface"]:
		for slot in range(SystemInfo["CommonInterface"]):
			config.ci.append(ConfigSubsection())
			config.ci[slot].canDescrambleMultipleServices = ConfigSelection(choices=[("auto", _("auto")), ("no", _("no")), ("yes", _("yes"))], default="auto")
			config.ci[slot].use_static_pin = ConfigYesNo(default=True)
			config.ci[slot].static_pin = ConfigPIN(default=0)
			config.ci[slot].show_ci_messages = ConfigYesNo(default=True)
			if SystemInfo["CI%dSupportsHighBitrates" % slot]:
				config.ci[slot].canHandleHighBitrates = ConfigYesNo(default=True)
				config.ci[slot].canHandleHighBitrates.slotid = slot
				config.ci[slot].canHandleHighBitrates.addNotifier(setCIBitrate)
			if SystemInfo["CI%dRelevantPidsRoutingSupport" % slot]:
				config.ci[slot].relevantPidsRouting = ConfigYesNo(default=False)
				config.ci[slot].relevantPidsRouting.slotid = slot
				config.ci[slot].relevantPidsRouting.addNotifier(setRelevantPidsRouting)
		if SystemInfo["CommonInterfaceCIDelay"]:
			config.cimisc.dvbCiDelay = ConfigSelection(default="256", choices=[("16", "16"), ("32", "32"), ("64", "64"), ("128", "128"), ("256", "256")])
			config.cimisc.dvbCiDelay.addNotifier(setdvbCiDelay)
	def loadConfigFile(self):
		print("[AutomaticVolumeAdjustmentConfig] Loading config file...")
		self.config = Config()
		if not os_path.exists(self.CONFIG_FILE):
			try:
				fd = os_open(self.CONFIG_FILE, os_O_RDWR | os_O_CREAT)
				os_close(fd)
			except Exception as e:
				print("Error: ", e)
		try:
			self.config.loadFromFile(self.CONFIG_FILE)
		except Exception as e:
			print("Error: ", e)
		self.config.entriescount = ConfigInteger(0)
		self.config.Entries = ConfigSubList()
		self.config.enable = ConfigYesNo(default=False)
		self.config.modus = ConfigSelection(choices=[("0", _("Automatic volume adjust")), ("1", _("Remember service volume value"))], default="0")
		self.config.adustvalue = ConfigSelectionNumber(-50, 50, 5, default=25)
		self.config.mpeg_max_volume = ConfigSelectionNumber(10, 100, 5, default=100)
		self.config.show_volumebar = ConfigYesNo(default=False)
		self.initConfig()
Example #5
0
    def createConfig(self):
        def setVlt(fancontrol, fanid, configElement):
            fancontrol.setVoltage(fanid, configElement.value)

        def setPWM(fancontrol, fanid, configElement):
            fancontrol.setPWM(fanid, configElement.value)

        config.fans = ConfigSubList()
        for fanid in range(self.getFanCount()):
            fan = ConfigSubsection()
            fan.vlt = ConfigSlider(default=15, increment=5, limits=(0, 255))
            fan.pwm = ConfigSlider(default=0, increment=5, limits=(0, 255))
            fan.vlt_standby = ConfigSlider(default=5,
                                           increment=5,
                                           limits=(0, 255))
            fan.pwm_standby = ConfigSlider(default=0,
                                           increment=5,
                                           limits=(0, 255))
            fan.vlt.addNotifier(boundFunction(setVlt, self, fanid))
            fan.pwm.addNotifier(boundFunction(setPWM, self, fanid))
            config.fans.append(fan)
Example #6
0
def InitCiConfig():
    config.ci = ConfigSubList()
    for slot in range(MAX_NUM_CI):
        config.ci.append(ConfigSubsection())
        config.ci[slot].canDescrambleMultipleServices = ConfigSelection(
            choices=[("auto", _("Auto")), ("no", _("No")), ("yes", _("Yes"))],
            default="auto")
        config.ci[slot].use_static_pin = ConfigYesNo(default=True)
        config.ci[slot].static_pin = ConfigPIN(default=0)
        config.ci[slot].show_ci_messages = ConfigYesNo(default=True)
        if SystemInfo["CommonInterfaceSupportsHighBitrates"]:
            config.ci[slot].canHandleHighBitrates = ConfigSelection(
                choices=[("no", _("No")), ("yes", _("Yes"))], default="yes")
            config.ci[slot].canHandleHighBitrates.slotid = slot
            config.ci[slot].canHandleHighBitrates.addNotifier(setCIBitrate)
        if SystemInfo["CommonInterfaceCIDelay"]:
            config.ci.dvbCiDelay = ConfigSelection(default="256",
                                                   choices=[("16"), ("32"),
                                                            ("64"), ("128"),
                                                            ("256")])
            config.ci.dvbCiDelay.addNotifier(setdvbCiDelay)
def InitParentalControl():
    global parentalControl
    parentalControl = ParentalControl()
    config.ParentalControl = ConfigSubsection()
    config.ParentalControl.configured = ConfigYesNo(default=True)  # [iq]
    config.ParentalControl.mode = ConfigSelection(default="simple",
                                                  choices=[
                                                      ("simple", _("simple")),
                                                      ("complex", _("complex"))
                                                  ])
    config.ParentalControl.storeservicepin = ConfigSelection(
        default="never",
        choices=[("never", _("never")), ("5", _("%d minutes") % 5),
                 ("30", _("%d minutes") % 30), ("60", _("%d minutes") % 60),
                 ("standby", _("until standby/restart"))])
    config.ParentalControl.servicepinactive = ConfigYesNo(default=False)
    config.ParentalControl.setuppinactive = ConfigYesNo(default=True)  # [iq]
    config.ParentalControl.type = ConfigSelection(default="blacklist",
                                                  choices=[(LIST_WHITELIST,
                                                            _("whitelist")),
                                                           (LIST_BLACKLIST,
                                                            _("blacklist"))])
    # iq - [
    #	config.ParentalControl.setuppin = ConfigPIN(default = -1)
    config.ParentalControl.setuppin = ConfigPIN(default=0000)
    # ]
    config.ParentalControl.mastersetuppin = ConfigPIN(default=2011)

    config.ParentalControl.retries = ConfigSubsection()
    config.ParentalControl.retries.setuppin = ConfigSubsection()
    config.ParentalControl.retries.setuppin.tries = ConfigInteger(default=3)
    config.ParentalControl.retries.setuppin.time = ConfigInteger(default=3)
    config.ParentalControl.retries.servicepin = ConfigSubsection()
    config.ParentalControl.retries.servicepin.tries = ConfigInteger(default=3)
    config.ParentalControl.retries.servicepin.time = ConfigInteger(default=3)

    config.ParentalControl.servicepin = ConfigSubList()

    for i in (0, 1, 2):
        config.ParentalControl.servicepin.append(ConfigPIN(default=-1))
Example #8
0
 def saveconfig(self):
     nim_config_list = []
     remoteAddress = self.getRemoteAddress(update=True)
     if config.clientmode.enabled.isChanged(
     ) and config.clientmode.enabled.value:  # switching to client mode
         # save normal mode config so it can be reinsated when returning to normal mode
         nim_config_list = []
         for x in config.Nims:
             nim_config_list.append(x.getSavedValue())
         import json
         config.clientmode.nim_cache.value = json.dumps(nim_config_list)
         config.clientmode.remote_fallback_enabled_cache.value = config.usage.remote_fallback_enabled.value
         config.clientmode.remote_fallback_cache.value = config.usage.remote_fallback.value
         # normal mode config values saved
     if config.clientmode.enabled.value:
         config.usage.remote_fallback_enabled.value = True
         config.usage.remote_fallback.value = "http://%s:%d" % (
             remoteAddress, config.clientmode.serverStreamingPort.value)
     elif config.clientmode.enabled.isChanged(
     ):  # switching back to normal mode
         # load nim config from config.clientmode.nimcache
         import json
         nim_config_list = json.loads(config.clientmode.nim_cache.value)
         config.clientmode.nim_cache.value = ""
         config.Nims = ConfigSubList()
         for x in nim_config_list:
             tuner = ConfigSubsection()
             tuner.setSavedValue(x)
             config.Nims.append(tuner)
         config.Nims.save()
         # nim config loaded... but needs restart
         # reinstate normal mode values
         config.usage.remote_fallback_enabled.value = config.clientmode.remote_fallback_enabled_cache.value
         config.usage.remote_fallback.value = config.clientmode.remote_fallback_cache.value
         # reset some client mode settings
         config.clientmode.remote_fallback_enabled_cache.value = False
         config.clientmode.remote_fallback_cache.value = ""
     config.usage.save()
     config.clientmode.save()
     configfile.save()
Example #9
0
def InitParentalControl():
    global parentalControl
    parentalControl = ParentalControl()
    config.ParentalControl = ConfigSubsection()
    config.ParentalControl.configured = ConfigYesNo(default=False)
    config.ParentalControl.mode = ConfigSelection(default="simple",
                                                  choices=[
                                                      ("simple", _("simple")),
                                                      ("complex", _("complex"))
                                                  ])
    config.ParentalControl.storeservicepin = ConfigSelection(
        default="never",
        choices=[("never", _("never")), ("5", _("%d minutes") % 5),
                 ("30", _("%d minutes") % 30), ("60", _("%d minutes") % 60),
                 ("standby", _("until standby/restart"))])
    config.ParentalControl.servicepinactive = ConfigYesNo(default=False)
    config.ParentalControl.setuppinactive = ConfigYesNo(default=False)
    config.ParentalControl.type = ConfigSelection(default="blacklist",
                                                  choices=[(LIST_WHITELIST,
                                                            _("whitelist")),
                                                           (LIST_BLACKLIST,
                                                            _("blacklist"))])
    config.ParentalControl.setuppin = ConfigPIN(default=-1)

    config.ParentalControl.retries = ConfigSubsection()
    config.ParentalControl.retries.setuppin = ConfigSubsection()
    config.ParentalControl.retries.setuppin.tries = ConfigInteger(default=3)
    config.ParentalControl.retries.setuppin.time = ConfigInteger(default=3)
    config.ParentalControl.retries.servicepin = ConfigSubsection()
    config.ParentalControl.retries.servicepin.tries = ConfigInteger(default=3)
    config.ParentalControl.retries.servicepin.time = ConfigInteger(default=3)
    config.ParentalControl.servicepin = ConfigSubList()
    config.ParentalControl.age = ConfigSelection(
        default="18",
        choices=[(0, _("No age block"))] + list(
            (str(x), "%d+" % x) for x in range(3, 19)))

    for i in (0, 1, 2):
        config.ParentalControl.servicepin.append(ConfigPIN(default=-1))
Example #10
0
	def __init__(self, project):
		self.properties = ConfigSubsection()
		self.properties.menutitle = ConfigText(fixed_size = False, visible_width = 80)
		self.properties.menusubtitle = ConfigText(fixed_size = False, visible_width = 80)
		self.properties.aspect = ConfigSelection(choices = [("4:3", _("4:3")), ("16:9", _("16:9"))])
		self.properties.widescreen = ConfigSelection(choices = [("nopanscan", "nopanscan"), ("noletterbox", "noletterbox")])
		self.properties.autochapter = ConfigInteger(default = 0, limits = (0, 60))
		self.properties.audiotracks = ConfigSubList()
		self.DVBname = _("Title")
		self.DVBdescr = _("Description")
		self.DVBchannel = _("Channel")
		self.cuesheet = [ ]
		self.source = None
		self.filesize = 0
		self.estimatedDiskspace = 0
		self.inputfile = ""
		self.cutlist = [ ]
		self.chaptermarks = [ ]
		self.timeCreate = None
		self.VideoType = -1
		self.project = project
		self.length = 0
Example #11
0
 def getPMTInfo(self):
     service = self.session.nav.getCurrentService()
     audio = service and service.audioTracks()
     n = audio and audio.getNumberOfTracks() or 0
     if n > 0:
         from DVDTitle import ConfigFixedText
         from TitleProperties import languageChoices
         from Components.config import config, ConfigSubsection, ConfigSubList, ConfigSelection, ConfigYesNo
         self.t.properties.audiotracks = ConfigSubList()
         for x in range(n):
             i = audio.getTrackInfo(x)
             DVB_lang = i.getLanguage()
             description = i.getDescription()
             pid = str(i.getPID())
             if description == "MPEG":
                 description = "MP2"
             print("[DVDBurn] audiotrack pid:", pid, "description:",
                   description, "language:", DVB_lang, "count:", x,
                   "active:", (x < 8))
             self.t.properties.audiotracks.append(ConfigSubsection())
             self.t.properties.audiotracks[-1].active = ConfigYesNo(
                 default=(x < 8))
             self.t.properties.audiotracks[-1].format = ConfigFixedText(
                 description)
             self.t.properties.audiotracks[-1].language = ConfigSelection(
                 choices=languageChoices.choices,
                 default=languageChoices.getLanguage(DVB_lang))
             self.t.properties.audiotracks[-1].pid = ConfigFixedText(pid)
             self.t.properties.audiotracks[-1].DVB_lang = ConfigFixedText(
                 DVB_lang)
     sAspect = service.info().getInfo(iServiceInformation.sAspect)
     if sAspect in (1, 2, 5, 6, 9, 0xA, 0xD, 0xE):
         aspect = "4:3"
     else:
         aspect = "16:9"
     self.t.properties.aspect.setValue(aspect)
     self.t.VideoType = service.info().getInfo(
         iServiceInformation.sVideoType)
Example #12
0
	def getPMTInfo(self):
		service = self.session.nav.getCurrentService()
		audio = service and service.audioTracks()
		n = audio and audio.getNumberOfTracks() or 0
		if n > 0:
			from Title import ConfigFixedText
			from Project import iso639language
			from Components.config import config, ConfigSubsection, ConfigSubList, ConfigSelection, ConfigYesNo
			self.t.properties.audiotracks = ConfigSubList()
			for x in range(n):
				i = audio.getTrackInfo(x)
				DVB_lang = i.getLanguage()
				description = i.getDescription()
				pid = str(i.getPID())
				if description == "MPEG":
					description = "MP2"
				print "[audiotrack] pid:", pid, "description:", description, "language:", DVB_lang, "count:", x, "active:", (x < 8)
				self.t.properties.audiotracks.append(ConfigSubsection())
				self.t.properties.audiotracks[-1].active = ConfigYesNo(default = (x < 8))
				self.t.properties.audiotracks[-1].format = ConfigFixedText(description)
				choicelist = iso639language.getChoices()
				determined_language = iso639language.determineLanguage(DVB_lang)
				self.t.properties.audiotracks[-1].language = ConfigSelection(choices = choicelist, default=determined_language)
				self.t.properties.audiotracks[-1].pid = ConfigFixedText(pid)
				self.t.properties.audiotracks[-1].DVB_lang = ConfigFixedText(DVB_lang)
		sAspect = service.info().getInfo(iServiceInformation.sAspect)
		if sAspect in ( 1, 2, 5, 6, 9, 0xA, 0xD, 0xE ):
			aspect = "4:3"
		else:
			aspect = "16:9"
		self.t.properties.aspect.setValue(aspect)
		self.t.VideoType = service.info().getInfo(iServiceInformation.sVideoType)
		self.t.VideoPID = service.info().getInfo(iServiceInformation.sVideoPID)
		xres = service.info().getInfo(iServiceInformation.sVideoWidth)
		yres = service.info().getInfo(iServiceInformation.sVideoHeight)
		self.t.resolution = (xres, yres)
		self.t.framerate = service.info().getInfo(iServiceInformation.sFrameRate)
		self.t.progressive = service.info().getInfo(iServiceInformation.sProgressive)
    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")
Example #14
0
class TimerEntry(Screen, ConfigListScreen):

    def __init__(self, session, timer):
        Screen.__init__(self, session)
        self.timer = timer
        self.entryDate = None
        self.entryService = None
        self['HelpWindow'] = Pixmap()
        self['HelpWindow'].hide()
        self['oktext'] = Label(_('OK'))
        self['canceltext'] = Label(_('Cancel'))
        self['ok'] = Pixmap()
        self['cancel'] = Pixmap()
        self['summary_description'] = StaticText('')
        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,
         'up': self.keyUp,
         'down': self.keyDown}, -2)
        self.list = []
        ConfigListScreen.__init__(self, self.list, session=session)
        self.setTitle(_('PowerManager entry'))
        self.createSetup('config')
        return

    def createConfig(self):
        afterevent = {AFTEREVENT.NONE: 'nothing',
         AFTEREVENT.WAKEUP: 'wakeup',
         AFTEREVENT.WAKEUPTOSTANDBY: 'wakeuptostandby',
         AFTEREVENT.STANDBY: 'standby',
         AFTEREVENT.DEEPSTANDBY: 'deepstandby'}[self.timer.afterEvent]
        timertype = {TIMERTYPE.NONE: 'nothing',
         TIMERTYPE.WAKEUP: 'wakeup',
         TIMERTYPE.WAKEUPTOSTANDBY: 'wakeuptostandby',
         TIMERTYPE.AUTOSTANDBY: 'autostandby',
         TIMERTYPE.AUTODEEPSTANDBY: 'autodeepstandby',
         TIMERTYPE.STANDBY: 'standby',
         TIMERTYPE.DEEPSTANDBY: 'deepstandby',
         TIMERTYPE.REBOOT: 'reboot',
         TIMERTYPE.RESTART: 'restart'}[self.timer.timerType]
        weekday_table = ('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun')
        time_table = [(1, '1'),
         (3, '3'),
         (5, '5'),
         (10, '10'),
         (15, '15'),
         (30, '30'),
         (45, '45'),
         (60, '60'),
         (75, '75'),
         (90, '90'),
         (105, '105'),
         (120, '120'),
         (135, '135'),
         (150, '150'),
         (165, '165'),
         (180, '180'),
         (195, '195'),
         (210, '210'),
         (225, '225'),
         (240, '240'),
         (255, '255'),
         (270, '270'),
         (285, '285'),
         (300, '300')]
        traffic_table = [(10, '10'),
         (50, '50'),
         (100, '100'),
         (500, '500'),
         (1000, '1000')]
        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:
                        print 'Set to weekday ' + str(x)
                        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
        if SystemInfo['DeepstandbySupport']:
            shutdownString = _('go to deep standby')
        else:
            shutdownString = _('shut down')
        self.timerentry_timertype = ConfigSelection(choices=[('nothing', _('do nothing')),
         ('wakeup', _('wakeup')),
         ('wakeuptostandby', _('wakeup to standby')),
         ('autostandby', _('auto standby')),
         ('autodeepstandby', _('auto deepstandby')),
         ('standby', _('go to standby')),
         ('deepstandby', shutdownString),
         ('reboot', _('reboot system')),
         ('restart', _('restart GUI'))], default=timertype)
        self.timerentry_afterevent = ConfigSelection(choices=[('nothing', _('do nothing')),
         ('wakeup', _('wakeup')),
         ('wakeuptostandby', _('wakeup to standby')),
         ('standby', _('go to standby')),
         ('deepstandby', shutdownString),
         ('nothing', _('do nothing'))], default=afterevent)
        self.timerentry_type = ConfigSelection(choices=[('once', _('once')), ('repeated', _('repeated'))], default=type)
        self.timerentry_repeated = ConfigSelection(default=repeated, choices=[('daily', _('daily')),
         ('weekly', _('weekly')),
         ('weekdays', _('Mon-Fri')),
         ('user', _('user defined'))])
        self.timerrntry_autosleepdelay = ConfigSelection(choices=time_table, default=self.timer.autosleepdelay)
        self.timerentry_autosleeprepeat = ConfigSelection(choices=[('once', _('once')), ('repeated', _('repeated'))], default=self.timer.autosleeprepeat)
        self.timerrntry_autosleepinstandbyonly = ConfigSelection(choices=[('yes', _('Yes')), ('no', _('No'))], default=self.timer.autosleepinstandbyonly)
        self.timerrntry_autosleepwindow = ConfigSelection(choices=[('yes', _('Yes')), ('no', _('No'))], default=self.timer.autosleepwindow)
        self.timerrntry_autosleepbegin = ConfigClock(default=self.timer.autosleepbegin)
        self.timerrntry_autosleepend = ConfigClock(default=self.timer.autosleepend)
        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) / 60 > 4, choices=[(True, _('yes')), (False, _('no'))])
        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]))

        self.timerrntry_showExtended = ConfigSelection(default=self.timer.nettraffic == 'yes' or self.timer.netip == 'yes', choices=[(True, _('yes')), (False, _('no'))])
        self.timerrntry_nettraffic = ConfigSelection(choices=[('yes', _('Yes')), ('no', _('No'))], default=self.timer.nettraffic)
        self.timerrntry_trafficlimit = ConfigSelection(choices=traffic_table, default=self.timer.trafficlimit)
        self.timerrntry_netip = ConfigSelection(choices=[('yes', _('Yes')), ('no', _('No'))], default=self.timer.netip)
        self.timerrntry_ipadress = self.timer.ipadress.split(',')
        self.ipcount = ConfigSelectionNumber(default=len(self.timerrntry_ipadress), stepwidth=1, min=1, max=5)
        self.ipadressEntry = ConfigSubList()
        for x in (0, 1, 2, 3, 4, 5):
            try:
                self.ipadressEntry.append(ConfigIP(default=[ int(n) for n in self.timerrntry_ipadress[x].split('.') ] or [0,
                 0,
                 0,
                 0]))
            except:
                self.ipadressEntry.append(ConfigIP(default=[0,
                 0,
                 0,
                 0]))

        return

    def createSetup(self, widget):
        self.list = []
        self.timerType = getConfigListEntry(_('Timer type'), self.timerentry_timertype)
        self.list.append(self.timerType)
        self.timerTypeEntry = getConfigListEntry(_('Repeat type'), self.timerentry_type)
        self.entryStartTime = getConfigListEntry(_('Start time'), self.timerentry_starttime)
        self.entryShowEndTime = getConfigListEntry(_('Set end time'), self.timerentry_showendtime)
        self.entryEndTime = getConfigListEntry(_('End time'), self.timerentry_endtime)
        self.frequencyEntry = getConfigListEntry(_('Repeats'), self.timerentry_repeated)
        self.entryDate = getConfigListEntry(_('Date'), self.timerentry_date)
        self.repeatedbegindateEntry = getConfigListEntry(_('Starting on'), self.timerentry_repeatedbegindate)
        self.autosleepwindowEntry = getConfigListEntry(_('Restrict the active time range'), self.timerrntry_autosleepwindow)
        self.netExtendedEntry = getConfigListEntry(_('Show advanced settings'), self.timerrntry_showExtended)
        self.nettrafficEntry = getConfigListEntry(_('Enable Network Traffic check'), self.timerrntry_nettraffic)
        self.netipEntry = getConfigListEntry(_('Enable Network IP address check'), self.timerrntry_netip)
        self.ipcountEntry = getConfigListEntry(_('Select of the number'), self.ipcount)
        if self.timerentry_timertype.value == 'autostandby' or self.timerentry_timertype.value == 'autodeepstandby':
            if self.timerentry_timertype.value == 'autodeepstandby':
                self.list.append(getConfigListEntry(_('Only active when in standby'), self.timerrntry_autosleepinstandbyonly))
            self.list.append(getConfigListEntry(_('Sleep delay'), self.timerrntry_autosleepdelay))
            self.list.append(getConfigListEntry(_('Repeat type'), self.timerentry_autosleeprepeat))
            self.list.append(self.autosleepwindowEntry)
            if self.timerrntry_autosleepwindow.value == 'yes':
                self.list.append(getConfigListEntry(_('Start time'), self.timerrntry_autosleepbegin))
                self.list.append(getConfigListEntry(_('End time'), self.timerrntry_autosleepend))
            if self.timerentry_timertype.value == 'autodeepstandby':
                self.list.append(self.netExtendedEntry)
                if self.timerrntry_showExtended.value:
                    self.list.append(self.nettrafficEntry)
                    if self.timerrntry_nettraffic.value == 'yes':
                        self.list.append(getConfigListEntry(_('Lower limit in kilobits per seconds [kbit/s]'), self.timerrntry_trafficlimit))
                    self.list.append(self.netipEntry)
                    if self.timerrntry_netip.value == 'yes':
                        self.list.append(self.ipcountEntry)
                        for x in range(0, self.ipcount.value):
                            self.list.append(getConfigListEntry(('%d. ' + _('IP address')) % (x + 1), self.ipadressEntry[x]))

        else:
            self.list.append(self.timerTypeEntry)
            if self.timerentry_type.value == 'once':
                self.frequencyEntry = None
            else:
                self.list.append(self.frequencyEntry)
                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_type.value == 'once':
                self.list.append(self.entryDate)
            self.list.append(self.entryStartTime)
            self.list.append(self.entryShowEndTime)
            if self.timerentry_showendtime.value:
                self.list.append(self.entryEndTime)
                self.list.append(getConfigListEntry(_('After event'), self.timerentry_afterevent))
        self[widget].list = self.list
        self[widget].l.setList(self.list)
        self.checkSummary()
        return

    def createSummary(self):
        pass

    def checkSummary(self):
        self['summary_description'].text = self['config'].getCurrent()[0]

    def newConfig(self):
        if self['config'].getCurrent() in (self.timerType,
         self.timerTypeEntry,
         self.frequencyEntry,
         self.entryShowEndTime,
         self.autosleepwindowEntry,
         self.netExtendedEntry,
         self.nettrafficEntry,
         self.netipEntry,
         self.ipcountEntry):
            self.createSetup('config')

    def keyLeft(self):
        ConfigListScreen.keyLeft(self)
        self.newConfig()

    def keyRight(self):
        ConfigListScreen.keyRight(self)
        self.newConfig()

    def keySelect(self):
        cur = self['config'].getCurrent()
        self.keyGo()

    def keyUp(self):
        self['config'].moveUp()
        self.checkSummary()

    def keyDown(self):
        self['config'].moveDown()
        self.checkSummary()

    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
        return (begin, end)

    def keyGo(self, result = None):
        if not self.timerentry_showendtime.value:
            self.timerentry_endtime.value = self.timerentry_starttime.value
        self.timer.resetRepeated()
        if self.timerentry_type.value == 'once':
            self.timer.begin, self.timer.end = self.getBeginEnd()
        if self.timerentry_timertype.value == 'autostandby' or self.timerentry_timertype.value == 'autodeepstandby':
            self.timer.begin = int(time()) + 10
            self.timer.end = self.timer.begin
            self.timer.autosleepinstandbyonly = self.timerrntry_autosleepinstandbyonly.value
            self.timer.autosleepdelay = self.timerrntry_autosleepdelay.value
            self.timer.autosleeprepeat = self.timerentry_autosleeprepeat.value
            self.timerentry_showendtime.value = False
        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
        endaction = self.timerentry_showendtime.value
        if (self.timer.end - self.timer.begin) / 60 < 5 or self.timerentry_showendtime.value is False:
            self.timerentry_afterevent.value = 'nothing'
            self.timer.end = self.timer.begin
            if endaction:
                self.session.open(MessageBox, _('Difference between timer begin and end must be equal or greater than %d minutes.\nEnd Action was disabled !') % 5, MessageBox.TYPE_INFO, timeout=30)
        self.timer.timerType = {'nothing': TIMERTYPE.NONE,
         'wakeup': TIMERTYPE.WAKEUP,
         'wakeuptostandby': TIMERTYPE.WAKEUPTOSTANDBY,
         'autostandby': TIMERTYPE.AUTOSTANDBY,
         'autodeepstandby': TIMERTYPE.AUTODEEPSTANDBY,
         'standby': TIMERTYPE.STANDBY,
         'deepstandby': TIMERTYPE.DEEPSTANDBY,
         'reboot': TIMERTYPE.REBOOT,
         'restart': TIMERTYPE.RESTART}[self.timerentry_timertype.value]
        self.timer.afterEvent = {'nothing': AFTEREVENT.NONE,
         'wakeup': AFTEREVENT.WAKEUP,
         'wakeuptostandby': AFTEREVENT.WAKEUPTOSTANDBY,
         'standby': AFTEREVENT.STANDBY,
         'deepstandby': AFTEREVENT.DEEPSTANDBY}[self.timerentry_afterevent.value]
        self.timer.autosleepwindow = self.timerrntry_autosleepwindow.value
        self.timer.autosleepbegin = self.getTimestamp(time(), self.timerrntry_autosleepbegin.value)
        self.timer.autosleepend = self.getTimestamp(time(), self.timerrntry_autosleepend.value)
        self.timer.nettraffic = self.timerrntry_nettraffic.value
        self.timer.trafficlimit = self.timerrntry_trafficlimit.value
        self.timer.netip = self.timerrntry_netip.value
        self.timer.ipadress = '%d.%d.%d.%d' % (self.ipadressEntry[0].value[0],
         self.ipadressEntry[0].value[1],
         self.ipadressEntry[0].value[2],
         self.ipadressEntry[0].value[3])
        for x in range(1, self.ipcount.value):
            self.timer.ipadress += ',%d.%d.%d.%d' % (self.ipadressEntry[x].value[0],
             self.ipadressEntry[x].value[1],
             self.ipadressEntry[x].value[2],
             self.ipadressEntry[x].value[3])

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

    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 saveTimer(self):
        self.session.nav.PowerTimer.saveTimer()

    def keyCancel(self):
        self.close((False,))
Example #15
0
class TimerEntry(Screen, ConfigListScreen):
	def __init__(self, session, timer):
		Screen.__init__(self, session)
		self.timer = timer

		self.entryDate = None
		self.entryService = None

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

		self.createConfig()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	def tagEditFinished(self, ret):
		if ret is not None:
			self.timerentry_tags = ret
			self.timerentry_tagsset.setChoices([not ret and "None" or " ".join(ret)])
			self["config"].invalidate(self.tagsSet)
Example #16
0
from Plugins.Plugin import PluginDescriptor
from enigma import iPlayableService
from Components.ServiceEventTracker import ServiceEventTracker
from Components.config import config, getConfigListEntry, ConfigSubsection, ConfigSubList, ConfigInteger, ConfigYesNo, ConfigText, ConfigSelection
from Components.ConfigList import ConfigListScreen
#############
from enigma import ePoint, eSize


###############################################################################
myname = "AntiScrollbar"

config.plugins.antiscrollbar = ConfigSubsection()
config.plugins.antiscrollbar.autostart = ConfigYesNo(default=True)
config.plugins.antiscrollbar.modescount = ConfigInteger(0)
config.plugins.antiscrollbar.mode = ConfigSubList()


def initConfig():
    modescount = config.plugins.antiscrollbar.modescount.value
    if modescount == 0:
        pass
    else:
        i = 0
        while i < modescount:
            print "[" + myname + ".initConfig] i is %s" % i
            config.plugins.antiscrollbar.mode.append(ConfigSubsection())
            config.plugins.antiscrollbar.mode[i].sref = ConfigText("")
            config.plugins.antiscrollbar.mode[i].sizex = ConfigInteger(0)
            config.plugins.antiscrollbar.mode[i].sizey = ConfigInteger(0)
            config.plugins.antiscrollbar.mode[i].posx = ConfigInteger(0)
Example #17
0
from enigma import ePicLoad, eRect, eSize, gPixmapPtr
from Components.AVSwitch import AVSwitch
from Components.config import ConfigSubsection, ConfigSubList, ConfigInteger, config
from setup import initConfig, MSNWeatherPluginEntriesListConfigScreen
from MSNWeather import MSNWeather
import time

try:
	from Components.WeatherMSN import weathermsn
	WeatherMSNComp = weathermsn
except:
	WeatherMSNComp = None

config.plugins.WeatherPlugin = ConfigSubsection()
config.plugins.WeatherPlugin.entrycount =  ConfigInteger(0)
config.plugins.WeatherPlugin.Entry = ConfigSubList()
initConfig()


def main(session,**kwargs):
	session.open(MSNWeatherPlugin)

def Plugins(**kwargs):
	list = [PluginDescriptor(name=_("Weather Plugin"), description=_("Show Weather Forecast"), where = [PluginDescriptor.WHERE_PLUGINMENU, PluginDescriptor.WHERE_EXTENSIONSMENU], icon = "weather.png", fnc=main)]
	return list

class MSNWeatherPlugin(Screen):

	skin = """
		<screen name="MSNWeatherPlugin" position="center,center" size="664,340" title="Weather Plugin">
			<widget render="Label" source="caption" position="10,20" zPosition="1" size="600,28" font="Regular;24" transparent="1"/>
Example #18
0
    def readSkinPartScreens(self, partpath, partname):
        part = []
        screen = []
        lines = []
        self.screenlist[self.idx] = ConfigSubList()

        lidx = screenname = previewfile = description = ''
        enabled = p_nfo = s_nfo = False

        if path.isfile(partpath + partname + '.xml'):
            f = open(partpath + partname + '.xml', 'r')
            lines = f.readlines()
            f.close()
            if path.isfile(partpath + partname + '.txt'):
                f = open(partpath + partname + '.txt', 'r')
                description = f.read()
                f.close()
            if path.isfile(partpath + partname + '.png'):
                previewfile = partname + '.png'
            elif path.isfile(partpath + partname + '.jpg'):
                previewfile = partname + '.jpg'

        idx = 0
        for line in lines:
            idx += 1
            if '<screen' in line or '</screen>' in line:
                if p_nfo:
                    description = description.replace(
                        '\t', '').lstrip('\n').rstrip('\n').strip()
                    part.append((partpath, partname, previewfile, description))
                    previewfile = description = ''
                    p_nfo = False
                elif s_nfo:
                    description = description.replace(
                        '\t', '').lstrip('\n').rstrip('\n').strip()
                    screen.append((lidx, screenname, previewfile,
                                   description.rstrip('\n'), enabled))
                    lidx = screenname = previewfile = description = ''
                    enabled = s_nfo = False

            if '<skin>' in line:
                p_nfo = True
            if '<screen' in line and not '#hide#' in line:
                s_nfo = True
                a = line.find('name=')
                b = line.find('"', a)
                c = line.find('"', b + 1)
                name = line[b + 1:c]
                #// fix old typo
                name = name.replace('#deactivatd#', '#deactivated#')
                #//
                sname = name.replace('#deactivated#', '')
                if path.isfile(partpath + sname + '.txt'):
                    f = open(partpath + sname + '.txt', 'r')
                    description = f.read()
                    f.close()
                if path.isfile(partpath + sname + '.png'):
                    previewfile = sname + '.png'
                elif path.isfile(partpath + sname + '.jpg'):
                    previewfile = sname + '.jpg'

                if '#deactivated#' in name:
                    screenname = name.replace('#deactivated#', '')
                    enabled = False
                else:
                    screenname = name
                    enabled = True
                lidx = idx

            if '#description#' in line:
                a = line.find('#description#')
                description += line[a + 13:]
            elif '#previewfile#' in line:
                a = line.find('#previewfile#')
                file = line[a + 13:].replace('\n', '').replace(
                    '\t', '').lstrip('/').strip()
                if path.isfile(partpath + file):
                    previewfile = file

        if not part:
            part.append((partpath, partname, previewfile, description))
        self.parts[self.idx] = part
        self.screens[self.idx] = screen

        idx = 0
        for screen in self.screens[self.idx]:
            self.screenlist[self.idx].append(ConfigYesNo(default=False))
            self.screenlist[self.idx][idx].value = self.screens[self.idx][idx][
                4]  #screen[4]
            idx += 1
Example #19
0
	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])
Example #20
0
class TimerEntry(Screen, ConfigListScreen):
	def __init__(self, session, timer):
		Screen.__init__(self, session)
		self.setup_title = _("Timer entry")
		self.timer = timer

		self.entryDate = None
		self.entryService = None

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

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

		self.createConfig()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	def createSummary(self):
		return SetupSummary

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

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

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

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

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

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

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

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

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

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

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

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

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

		return begin, end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		self.entryDate = None
		self.entryService = None

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

		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.setTitle(_("PowerManager entry"))
		self.createSetup("config")

	def createConfig(self):
		afterevent = {
			AFTEREVENT.NONE: "nothing",
			AFTEREVENT.WAKEUPTOSTANDBY: "wakeuptostandby",
			AFTEREVENT.STANDBY: "standby",
			AFTEREVENT.DEEPSTANDBY: "deepstandby"
			}[self.timer.afterEvent]

		timertype = {
			TIMERTYPE.WAKEUP: "wakeup",
			TIMERTYPE.WAKEUPTOSTANDBY: "wakeuptostandby",
			TIMERTYPE.AUTOSTANDBY: "autostandby",
			TIMERTYPE.AUTODEEPSTANDBY: "autodeepstandby",
			TIMERTYPE.STANDBY: "standby",
			TIMERTYPE.DEEPSTANDBY: "deepstandby",
			TIMERTYPE.REBOOT: "reboot",
			TIMERTYPE.RESTART: "restart"
			}[self.timer.timerType]

		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

		autosleepinstandbyonly = self.timer.autosleepinstandbyonly
		autosleepdelay = self.timer.autosleepdelay
		autosleeprepeat = self.timer.autosleeprepeat

		if SystemInfo["DeepstandbySupport"]:
			shutdownString = _("go to deep standby")
		else:
			shutdownString = _("shut down")
		self.timerentry_timertype = ConfigSelection(choices = [("wakeup", _("wakeup")),("wakeuptostandby", _("wakeup to standby")), ("autostandby", _("auto standby")), ("autodeepstandby", _("auto deepstandby")), ("standby", _("go to standby")), ("deepstandby", shutdownString), ("reboot", _("reboot system")), ("restart", _("restart GUI"))], default = timertype)
		self.timerentry_afterevent = ConfigSelection(choices = [("nothing", _("do nothing")), ("wakeuptostandby", _("wakeup to standby")), ("standby", _("go to standby")), ("deepstandby", shutdownString), ("nothing", _("do nothing"))], default = afterevent)
		self.timerentry_type = ConfigSelection(choices = [("once",_("once")), ("repeated", _("repeated"))], default = type)

		self.timerentry_repeated = ConfigSelection(default = repeated, choices = [("daily", _("daily")), ("weekly", _("weekly")), ("weekdays", _("Mon-Fri")), ("user", _("user defined"))])
		self.timerrntry_autosleepdelay = ConfigInteger(default=autosleepdelay, limits = (10, 300))
		self.timerentry_autosleeprepeat = ConfigSelection(choices = [("once",_("once")), ("repeated", _("repeated"))], default = autosleeprepeat)
		self.timerrntry_autosleepinstandbyonly = ConfigSelection(choices = [("yes",_("Yes")), ("no", _("No"))],default=autosleepinstandbyonly)

		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) /60 ) > 1), choices = [(True, _("yes")), (False, _("no"))])

		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]))

	def createSetup(self, widget):
		self.list = []
		self.timerType = getConfigListEntry(_("Timer type"), self.timerentry_timertype)
		self.list.append(self.timerType)


		if self.timerentry_timertype.value == "autostandby" or self.timerentry_timertype.value == "autodeepstandby":
			if self.timerentry_timertype.value == "autodeepstandby":
				self.list.append(getConfigListEntry(_("Only active when in standby"), self.timerrntry_autosleepinstandbyonly))
			self.list.append(getConfigListEntry(_("Sleep delay"), self.timerrntry_autosleepdelay))
			self.list.append(getConfigListEntry(_("Repeat type"), self.timerentry_autosleeprepeat))
			self.timerTypeEntry = getConfigListEntry(_("Repeat type"), self.timerentry_type)
			self.entryShowEndTime = getConfigListEntry(_("Set end time"), self.timerentry_showendtime)
			self.frequencyEntry = getConfigListEntry(_("Repeats"), self.timerentry_repeated)
		else:
			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.list.append(self.entryShowEndTime)
			self.entryEndTime = getConfigListEntry(_("End time"), self.timerentry_endtime)
			if self.timerentry_showendtime.value:
				self.list.append(self.entryEndTime)

			self.list.append(getConfigListEntry(_("After event"), self.timerentry_afterevent))

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

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

	def keyLeft(self):
		ConfigListScreen.keyLeft(self)
		self.newConfig()

	def keyRight(self):
		ConfigListScreen.keyRight(self)
		self.newConfig()

	def keySelect(self):
		cur = self["config"].getCurrent()
		self.keyGo()

	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, result = None):
		if not self.timerentry_showendtime.value:
			self.timerentry_endtime.value = self.timerentry_starttime.value

		self.timer.resetRepeated()
		self.timer.timerType = {
			"wakeup": TIMERTYPE.WAKEUP,
			"wakeuptostandby": TIMERTYPE.WAKEUPTOSTANDBY,
			"autostandby": TIMERTYPE.AUTOSTANDBY,
			"autodeepstandby": TIMERTYPE.AUTODEEPSTANDBY,
			"standby": TIMERTYPE.STANDBY,
			"deepstandby": TIMERTYPE.DEEPSTANDBY,
			"reboot": TIMERTYPE.REBOOT,
			"restart": TIMERTYPE.RESTART
			}[self.timerentry_timertype.value]
		self.timer.afterEvent = {
			"nothing": AFTEREVENT.NONE,
			"wakeuptostandby": AFTEREVENT.WAKEUPTOSTANDBY,
			"standby": AFTEREVENT.STANDBY,
			"deepstandby": AFTEREVENT.DEEPSTANDBY
			}[self.timerentry_afterevent.value]

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

		if self.timerentry_timertype.value == "autostandby" or self.timerentry_timertype.value == "autodeepstandby":
			self.timer.begin = int(time()) + 10
			self.timer.end = self.timer.begin
			self.timer.autosleepinstandbyonly = self.timerrntry_autosleepinstandbyonly.value
			self.timer.autosleepdelay = self.timerrntry_autosleepdelay.value
			self.timer.autosleeprepeat = self.timerentry_autosleeprepeat.value
		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

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

	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 saveTimer(self):
		self.session.nav.PowerTimer.saveTimer()

	def keyCancel(self):
		self.close((False,))
Example #22
0
    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
Example #23
0
class TimerEntry(Screen, ConfigListScreen):

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

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

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

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

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

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

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

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

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

    def createSummary(self):
        return SetupSummary

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def tagEditFinished(self, ret):
        if ret is not None:
            self.timerentry_tags = ret
            self.timerentry_tagsset.setChoices([not ret and 'None' or ' '.join(ret)])
            self['config'].invalidate(self.tagsSet)
        return
Example #24
0
    def createConfig(self):
        afterevent = {AFTEREVENT.NONE: 'nothing',
         AFTEREVENT.WAKEUP: 'wakeup',
         AFTEREVENT.WAKEUPTOSTANDBY: 'wakeuptostandby',
         AFTEREVENT.STANDBY: 'standby',
         AFTEREVENT.DEEPSTANDBY: 'deepstandby'}[self.timer.afterEvent]
        timertype = {TIMERTYPE.NONE: 'nothing',
         TIMERTYPE.WAKEUP: 'wakeup',
         TIMERTYPE.WAKEUPTOSTANDBY: 'wakeuptostandby',
         TIMERTYPE.AUTOSTANDBY: 'autostandby',
         TIMERTYPE.AUTODEEPSTANDBY: 'autodeepstandby',
         TIMERTYPE.STANDBY: 'standby',
         TIMERTYPE.DEEPSTANDBY: 'deepstandby',
         TIMERTYPE.REBOOT: 'reboot',
         TIMERTYPE.RESTART: 'restart'}[self.timer.timerType]
        weekday_table = ('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun')
        time_table = [(1, '1'),
         (3, '3'),
         (5, '5'),
         (10, '10'),
         (15, '15'),
         (30, '30'),
         (45, '45'),
         (60, '60'),
         (75, '75'),
         (90, '90'),
         (105, '105'),
         (120, '120'),
         (135, '135'),
         (150, '150'),
         (165, '165'),
         (180, '180'),
         (195, '195'),
         (210, '210'),
         (225, '225'),
         (240, '240'),
         (255, '255'),
         (270, '270'),
         (285, '285'),
         (300, '300')]
        traffic_table = [(10, '10'),
         (50, '50'),
         (100, '100'),
         (500, '500'),
         (1000, '1000')]
        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:
                        print 'Set to weekday ' + str(x)
                        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
        if SystemInfo['DeepstandbySupport']:
            shutdownString = _('go to deep standby')
        else:
            shutdownString = _('shut down')
        self.timerentry_timertype = ConfigSelection(choices=[('nothing', _('do nothing')),
         ('wakeup', _('wakeup')),
         ('wakeuptostandby', _('wakeup to standby')),
         ('autostandby', _('auto standby')),
         ('autodeepstandby', _('auto deepstandby')),
         ('standby', _('go to standby')),
         ('deepstandby', shutdownString),
         ('reboot', _('reboot system')),
         ('restart', _('restart GUI'))], default=timertype)
        self.timerentry_afterevent = ConfigSelection(choices=[('nothing', _('do nothing')),
         ('wakeup', _('wakeup')),
         ('wakeuptostandby', _('wakeup to standby')),
         ('standby', _('go to standby')),
         ('deepstandby', shutdownString),
         ('nothing', _('do nothing'))], default=afterevent)
        self.timerentry_type = ConfigSelection(choices=[('once', _('once')), ('repeated', _('repeated'))], default=type)
        self.timerentry_repeated = ConfigSelection(default=repeated, choices=[('daily', _('daily')),
         ('weekly', _('weekly')),
         ('weekdays', _('Mon-Fri')),
         ('user', _('user defined'))])
        self.timerrntry_autosleepdelay = ConfigSelection(choices=time_table, default=self.timer.autosleepdelay)
        self.timerentry_autosleeprepeat = ConfigSelection(choices=[('once', _('once')), ('repeated', _('repeated'))], default=self.timer.autosleeprepeat)
        self.timerrntry_autosleepinstandbyonly = ConfigSelection(choices=[('yes', _('Yes')), ('no', _('No'))], default=self.timer.autosleepinstandbyonly)
        self.timerrntry_autosleepwindow = ConfigSelection(choices=[('yes', _('Yes')), ('no', _('No'))], default=self.timer.autosleepwindow)
        self.timerrntry_autosleepbegin = ConfigClock(default=self.timer.autosleepbegin)
        self.timerrntry_autosleepend = ConfigClock(default=self.timer.autosleepend)
        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) / 60 > 4, choices=[(True, _('yes')), (False, _('no'))])
        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]))

        self.timerrntry_showExtended = ConfigSelection(default=self.timer.nettraffic == 'yes' or self.timer.netip == 'yes', choices=[(True, _('yes')), (False, _('no'))])
        self.timerrntry_nettraffic = ConfigSelection(choices=[('yes', _('Yes')), ('no', _('No'))], default=self.timer.nettraffic)
        self.timerrntry_trafficlimit = ConfigSelection(choices=traffic_table, default=self.timer.trafficlimit)
        self.timerrntry_netip = ConfigSelection(choices=[('yes', _('Yes')), ('no', _('No'))], default=self.timer.netip)
        self.timerrntry_ipadress = self.timer.ipadress.split(',')
        self.ipcount = ConfigSelectionNumber(default=len(self.timerrntry_ipadress), stepwidth=1, min=1, max=5)
        self.ipadressEntry = ConfigSubList()
        for x in (0, 1, 2, 3, 4, 5):
            try:
                self.ipadressEntry.append(ConfigIP(default=[ int(n) for n in self.timerrntry_ipadress[x].split('.') ] or [0,
                 0,
                 0,
                 0]))
            except:
                self.ipadressEntry.append(ConfigIP(default=[0,
                 0,
                 0,
                 0]))

        return
Example #25
0
class TimerEntry(Screen, ConfigListScreen):
	def __init__(self, session, timer):
		Screen.__init__(self, session)
		self.timer = timer

		self.entryDate = None
		self.entryService = None

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

		self.createConfig()

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

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

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

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

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

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

			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)
Example #26
0
class TimerEntry(Screen, ConfigListScreen):
    def __init__(self, session, timer):
        Screen.__init__(self, session)
        self.setup_title = _("Timer entry")
        self.timer = timer

        self.entryDate = None
        self.entryService = None

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

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

        self.createConfig()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def createSummary(self):
        return SetupSummary

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return begin, end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def tagEditFinished(self, ret):
        if ret is not None:
            self.timerentry_tags = ret
            self.timerentry_tagsset.setChoices(
                [not ret and "None" or " ".join(ret)])
            self["config"].invalidate(self.tagsSet)
Example #27
0
import Plugins.Plugin
from Components.config import config, ConfigSubsection, ConfigSelection, ConfigInteger, ConfigSubList, ConfigSubDict, ConfigText, configfile, ConfigYesNo
from skin import loadSkin
from Components.Language import language
from Tools.Directories import resolveFilename, SCOPE_LANGUAGE, SCOPE_PLUGINS
import os, gettext

currentmcversion = "093"
currentmcplatform = "mipsel"

config.plugins.mc_favorites = ConfigSubsection()
config.plugins.mc_favorites.foldercount = ConfigInteger(0)
config.plugins.mc_favorites.folders = ConfigSubList()

config.plugins.mc_globalsettings = ConfigSubsection()
config.plugins.mc_globalsettings.showinmainmenu = ConfigYesNo(default=True)
config.plugins.mc_globalsettings.showinextmenu = ConfigYesNo(default=False)
config.plugins.mc_globalsettings.currentversion = ConfigInteger(0, (0, 999))
config.plugins.mc_globalsettings.currentplatform = ConfigText(
    default=currentmcplatform)

config.plugins.mc_globalsettings.dst_top = ConfigInteger(0, (0, 999))
config.plugins.mc_globalsettings.dst_left = ConfigInteger(0, (0, 999))
config.plugins.mc_globalsettings.dst_width = ConfigInteger(720, (1, 720))
config.plugins.mc_globalsettings.dst_height = ConfigInteger(576, (1, 576))

config.plugins.mc_globalsettings.currentskin = ConfigSubsection()
config.plugins.mc_globalsettings.currentskin.path = ConfigText(
    default="defaultHD/skin.xml")

config.plugins.mc_globalsettings.currentversion.value = currentmcversion
Example #28
0
	def createConfig(self):
		afterevent = {
			AFTEREVENT.NONE: "nothing",
			AFTEREVENT.WAKEUPTOSTANDBY: "wakeuptostandby",
			AFTEREVENT.STANDBY: "standby",
			AFTEREVENT.DEEPSTANDBY: "deepstandby"
			}[self.timer.afterEvent]

		timertype = {
			TIMERTYPE.WAKEUP: "wakeup",
			TIMERTYPE.WAKEUPTOSTANDBY: "wakeuptostandby",
			TIMERTYPE.AUTOSTANDBY: "autostandby",
			TIMERTYPE.AUTODEEPSTANDBY: "autodeepstandby",
			TIMERTYPE.STANDBY: "standby",
			TIMERTYPE.DEEPSTANDBY: "deepstandby",
			TIMERTYPE.REBOOT: "reboot",
			TIMERTYPE.RESTART: "restart"
			}[self.timer.timerType]

		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

		autosleepinstandbyonly = self.timer.autosleepinstandbyonly
		autosleepdelay = self.timer.autosleepdelay
		autosleeprepeat = self.timer.autosleeprepeat

		if SystemInfo["DeepstandbySupport"]:
			shutdownString = _("go to deep standby")
		else:
			shutdownString = _("shut down")
		self.timerentry_timertype = ConfigSelection(choices = [("wakeup", _("wakeup")),("wakeuptostandby", _("wakeup to standby")), ("autostandby", _("auto standby")), ("autodeepstandby", _("auto deepstandby")), ("standby", _("go to standby")), ("deepstandby", shutdownString), ("reboot", _("reboot system")), ("restart", _("restart GUI"))], default = timertype)
		self.timerentry_afterevent = ConfigSelection(choices = [("nothing", _("do nothing")), ("wakeuptostandby", _("wakeup to standby")), ("standby", _("go to standby")), ("deepstandby", shutdownString), ("nothing", _("do nothing"))], default = afterevent)
		self.timerentry_type = ConfigSelection(choices = [("once",_("once")), ("repeated", _("repeated"))], default = type)

		self.timerentry_repeated = ConfigSelection(default = repeated, choices = [("daily", _("daily")), ("weekly", _("weekly")), ("weekdays", _("Mon-Fri")), ("user", _("user defined"))])
		self.timerrntry_autosleepdelay = ConfigInteger(default=autosleepdelay, limits = (10, 300))
		self.timerentry_autosleeprepeat = ConfigSelection(choices = [("once",_("once")), ("repeated", _("repeated"))], default = autosleeprepeat)
		self.timerrntry_autosleepinstandbyonly = ConfigSelection(choices = [("yes",_("Yes")), ("no", _("No"))],default=autosleepinstandbyonly)

		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) /60 ) > 1), choices = [(True, _("yes")), (False, _("no"))])

		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]))
Example #29
0
class TimerEntry(Screen, ConfigListScreen, HelpableScreen):
	def __init__(self, session, timer):
		Screen.__init__(self, session)
		HelpableScreen.__init__(self)
		self.setup_title = _("Timer entry")
		self.timer = timer

		self.entryDate = None
		self.entryService = None

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

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

		self.createConfig()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	def createSummary(self):
		return SetupSummary

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		return begin, end

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	def tagEditFinished(self, ret):
		if ret is not None:
			self.timerentry_tags = ret
			self.timerentry_tagsset.setChoices([not ret and "None" or " ".join(ret)])
			self["config"].invalidate(self.tagsSet)
Example #30
0
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Components.ConfigList import ConfigListScreen
from Components.config import config, getConfigListEntry, ConfigSubsection, ConfigInteger, ConfigYesNo, ConfigText, ConfigSelection, ConfigSubList, ConfigIP
from Components.Sources.StaticText import StaticText
from Components.MenuList import MenuList
from Components.MultiContent import MultiContentEntryText
from Components.ActionMap import ActionMap

config.plugins.vTuner = ConfigSubsection()
config.plugins.vTuner.client = ConfigSubsection()
config.plugins.vTuner.client.enabled = ConfigYesNo(default=True)
config.plugins.vTuner.client.mode = ConfigSubList()

for i in [0, 1, 2]:
    mode = ConfigSubsection()
    if i == 0:
        # first type must not be none
        mode.type = ConfigSelection(
            default="-s2",
            choices=[("-s2", _("DVB-S2 connected to DVB-S/S2")),
                     ("-c", _("DVB-C")), ("-t", _("DVB-T")),
                     ("-S2", _("DVB-S/S2 connected to DVB-S2")),
                     ("-s", _("DVB-S connected to DVB-S/S2")),
                     ("-S", _("DVB-S connected to DVB-S"))])
    else:
        mode.type = ConfigSelection(
            default="",
            choices=[("", _("unused")),
                     ("-s2", _("DVB-S2 connected to DVB-S/S2")),
                     ("-c", _("DVB-C")), ("-t", _("DVB-T")),
Example #31
0
class TimerEntry(Screen, ConfigListScreen):
    def __init__(self, session, timer):
        Screen.__init__(self, session)
        self.setTitle(_("Power Timer Edit"))

        self.timer = timer

        self.entryDate = None
        self.entryService = None

        # No ConfigText fields in TimerEntry so these are not currently used.
        #self["HelpWindow"] = Pixmap()
        #self["HelpWindow"].hide()
        #self["VKeyIcon"] = Boolean(False)

        self["key_green"] = self["oktext"] = Label(_("OK"))
        self["key_red"] = 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):
        afterevent = {
            AFTEREVENT.NONE: "nothing",
            AFTEREVENT.WAKEUPTOSTANDBY: "wakeuptostandby",
            AFTEREVENT.STANDBY: "standby",
            AFTEREVENT.DEEPSTANDBY: "deepstandby"
        }[self.timer.afterEvent]

        timertype = {
            TIMERTYPE.WAKEUP: "wakeup",
            TIMERTYPE.WAKEUPTOSTANDBY: "wakeuptostandby",
            TIMERTYPE.AUTOSTANDBY: "autostandby",
            TIMERTYPE.AUTODEEPSTANDBY: "autodeepstandby",
            TIMERTYPE.STANDBY: "standby",
            TIMERTYPE.DEEPSTANDBY: "deepstandby",
            TIMERTYPE.REBOOT: "reboot",
            TIMERTYPE.RESTART: "restart"
        }[self.timer.timerType]

        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 "[PowerTimerEntry] 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

        autosleepinstandbyonly = self.timer.autosleepinstandbyonly
        autosleepdelay = self.timer.autosleepdelay
        autosleeprepeat = self.timer.autosleeprepeat

        if SystemInfo["DeepstandbySupport"]:
            shutdownString = _("go to deep standby")
        else:
            shutdownString = _("shut down")
        self.timerentry_timertype = ConfigSelection(choices=[
            ("wakeup", _("wakeup")),
            ("wakeuptostandby", _("wakeup to standby")),
            ("autostandby", _("auto standby")),
            ("autodeepstandby", _("auto deepstandby")),
            ("standby", _("go to standby")), ("deepstandby", shutdownString),
            ("reboot", _("reboot system")), ("restart", _("restart GUI"))
        ],
                                                    default=timertype)
        self.timerentry_afterevent = ConfigSelection(choices=[
            ("nothing", _("do nothing")),
            ("wakeuptostandby", _("wakeup to standby")),
            ("standby", _("go to standby")), ("deepstandby", shutdownString),
            ("nothing", _("do nothing"))
        ],
                                                     default=afterevent)
        self.timerentry_type = ConfigSelection(choices=[("once", _("once")),
                                                        ("repeated",
                                                         _("repeated"))],
                                               default=type)

        self.timerentry_repeated = ConfigSelection(
            default=repeated,
            choices=[("daily", _("daily")), ("weekly", _("weekly")),
                     ("weekdays", _("Mon-Fri")), ("user", _("user defined"))])
        self.timerentry_autosleepdelay = ConfigInteger(default=autosleepdelay,
                                                       limits=(10, 300))
        self.timerentry_autosleeprepeat = ConfigSelection(
            choices=[("once", _("once")), ("repeated", _("repeated"))],
            default=autosleeprepeat)
        self.timerentry_autosleepinstandbyonly = ConfigSelection(
            choices=[("yes", _("Yes")), ("no", _("No"))],
            default=autosleepinstandbyonly)

        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 = ConfigYesNo(
            default=(((self.timer.end - self.timer.begin) / 60) > 1))

        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]))

    def createSetup(self, widget):
        self.list = []
        self.timerType = getConfigListEntry(_("Timer type"),
                                            self.timerentry_timertype)
        self.list.append(self.timerType)

        if self.timerentry_timertype.value == "autostandby" or self.timerentry_timertype.value == "autodeepstandby":
            if self.timerentry_timertype.value == "autodeepstandby":
                self.list.append(
                    getConfigListEntry(_("Only active when in standby"),
                                       self.timerentry_autosleepinstandbyonly))
            self.list.append(
                getConfigListEntry(_("Sleep delay"),
                                   self.timerentry_autosleepdelay))
            self.list.append(
                getConfigListEntry(_("Repeat type"),
                                   self.timerentry_autosleeprepeat))
            self.timerTypeEntry = getConfigListEntry(_("Repeat type"),
                                                     self.timerentry_type)
            self.entryShowEndTime = getConfigListEntry(
                _("Set end time"), self.timerentry_showendtime)
            self.frequencyEntry = getConfigListEntry(_("Repeats"),
                                                     self.timerentry_repeated)
        else:
            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.list.append(self.entryShowEndTime)
            self.entryEndTime = getConfigListEntry(_("End time"),
                                                   self.timerentry_endtime)
            if self.timerentry_showendtime.value:
                self.list.append(self.entryEndTime)

            self.list.append(
                getConfigListEntry(_("After event"),
                                   self.timerentry_afterevent))

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

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

    def keyLeft(self):
        ConfigListScreen.keyLeft(self)
        self.newConfig()

    def keyRight(self):
        ConfigListScreen.keyRight(self)
        self.newConfig()

    def keySelect(self):
        cur = self["config"].getCurrent()
        self.keyGo()

    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, result=None):
        if not self.timerentry_showendtime.value:
            self.timerentry_endtime.value = self.timerentry_starttime.value

        self.timer.resetRepeated()
        self.timer.timerType = {
            "wakeup": TIMERTYPE.WAKEUP,
            "wakeuptostandby": TIMERTYPE.WAKEUPTOSTANDBY,
            "autostandby": TIMERTYPE.AUTOSTANDBY,
            "autodeepstandby": TIMERTYPE.AUTODEEPSTANDBY,
            "standby": TIMERTYPE.STANDBY,
            "deepstandby": TIMERTYPE.DEEPSTANDBY,
            "reboot": TIMERTYPE.REBOOT,
            "restart": TIMERTYPE.RESTART
        }[self.timerentry_timertype.value]
        self.timer.afterEvent = {
            "nothing": AFTEREVENT.NONE,
            "wakeuptostandby": AFTEREVENT.WAKEUPTOSTANDBY,
            "standby": AFTEREVENT.STANDBY,
            "deepstandby": AFTEREVENT.DEEPSTANDBY
        }[self.timerentry_afterevent.value]

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

        if self.timerentry_timertype.value == "autostandby" or self.timerentry_timertype.value == "autodeepstandby":
            self.timer.begin = int(time()) + 10
            self.timer.end = self.timer.begin
            self.timer.autosleepinstandbyonly = self.timerentry_autosleepinstandbyonly.value
            self.timer.autosleepdelay = self.timerentry_autosleepdelay.value
            self.timer.autosleeprepeat = self.timerentry_autosleeprepeat.value
            # Ensure that the timer repeated is cleared if we have an autosleeprepeat
            if self.timerentry_type.value == "repeated":
                self.timer.resetRepeated()
                self.timerentry_type.value = "once"  # Stop it being set again

        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

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


# The following four functions check for the item to be changed existing
# as for auto[deep]standby timers it doesn't, so we'll crash otherwise.
#

    def incrementStart(self):
        if not hasattr(self, "entryStartTime"):
            return
        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):
        if not hasattr(self, "entryStartTime"):
            return
        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 not hasattr(self, "entryEndTime"):
            return
        if self.entryEndTime is not None:
            self.timerentry_endtime.increment()
            self["config"].invalidate(self.entryEndTime)

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

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

    def keyCancel(self):
        self.close((False, ))
Example #32
0
class TimerEntry(Screen, ConfigListScreen):
    def __init__(self, session, timer):
        Screen.__init__(self, session)
        self.timer = timer

        self.entryDate = None
        self.entryService = None

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

        self.createConfig()

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

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

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

        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)
Example #33
0
    def createConfig(self):
        afterevent = {
            AFTEREVENT.NONE: "nothing",
            AFTEREVENT.WAKEUPTOSTANDBY: "wakeuptostandby",
            AFTEREVENT.STANDBY: "standby",
            AFTEREVENT.DEEPSTANDBY: "deepstandby"
        }[self.timer.afterEvent]

        timertype = {
            TIMERTYPE.WAKEUP: "wakeup",
            TIMERTYPE.WAKEUPTOSTANDBY: "wakeuptostandby",
            TIMERTYPE.AUTOSTANDBY: "autostandby",
            TIMERTYPE.AUTODEEPSTANDBY: "autodeepstandby",
            TIMERTYPE.STANDBY: "standby",
            TIMERTYPE.DEEPSTANDBY: "deepstandby",
            TIMERTYPE.REBOOT: "reboot",
            TIMERTYPE.RESTART: "restart"
        }[self.timer.timerType]

        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 "[PowerTimerEntry] 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

        autosleepinstandbyonly = self.timer.autosleepinstandbyonly
        autosleepdelay = self.timer.autosleepdelay
        autosleeprepeat = self.timer.autosleeprepeat

        if SystemInfo["DeepstandbySupport"]:
            shutdownString = _("go to deep standby")
        else:
            shutdownString = _("shut down")
        self.timerentry_timertype = ConfigSelection(choices=[
            ("wakeup", _("wakeup")),
            ("wakeuptostandby", _("wakeup to standby")),
            ("autostandby", _("auto standby")),
            ("autodeepstandby", _("auto deepstandby")),
            ("standby", _("go to standby")), ("deepstandby", shutdownString),
            ("reboot", _("reboot system")), ("restart", _("restart GUI"))
        ],
                                                    default=timertype)
        self.timerentry_afterevent = ConfigSelection(choices=[
            ("nothing", _("do nothing")),
            ("wakeuptostandby", _("wakeup to standby")),
            ("standby", _("go to standby")), ("deepstandby", shutdownString),
            ("nothing", _("do nothing"))
        ],
                                                     default=afterevent)
        self.timerentry_type = ConfigSelection(choices=[("once", _("once")),
                                                        ("repeated",
                                                         _("repeated"))],
                                               default=type)

        self.timerentry_repeated = ConfigSelection(
            default=repeated,
            choices=[("daily", _("daily")), ("weekly", _("weekly")),
                     ("weekdays", _("Mon-Fri")), ("user", _("user defined"))])
        self.timerentry_autosleepdelay = ConfigInteger(default=autosleepdelay,
                                                       limits=(10, 300))
        self.timerentry_autosleeprepeat = ConfigSelection(
            choices=[("once", _("once")), ("repeated", _("repeated"))],
            default=autosleeprepeat)
        self.timerentry_autosleepinstandbyonly = ConfigSelection(
            choices=[("yes", _("Yes")), ("no", _("No"))],
            default=autosleepinstandbyonly)

        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 = ConfigYesNo(
            default=(((self.timer.end - self.timer.begin) / 60) > 1))

        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]))
Example #34
0
class SkinpartSettingsView(ConfigListScreen, Screen):
    skin = """
	<screen name="MyMetrixLiteOtherView" position="0,0" size="1280,720" flags="wfNoBorder" backgroundColor="transparent">
	<eLabel name="new eLabel" position="40,40" zPosition="-2" size="1200,640" backgroundColor="#00000000" transparent="0" />
	<widget source="titleText" position="60,55" size="590,50" render="Label" font="Regular; 40" foregroundColor="#00ffffff" backgroundColor="#00000000" valign="center" transparent="1" />
	<widget name="config" position="61,124" size="590,480" backgroundColor="#00000000" foregroundColor="#00ffffff" scrollbarMode="showOnDemand" transparent="1" />
	<widget source="cancelBtn" position="70,640" size="160,30" render="Label" font="Regular; 20" foregroundColor="#00ffffff" backgroundColor="#00000000" halign="left" transparent="1" />
	<widget source="saveBtn" position="257,640" size="160,30" render="Label" font="Regular; 20" foregroundColor="#00ffffff" backgroundColor="#00000000" halign="left" transparent="1" />
	<widget source="defaultsBtn" position="445,640" size="160,30" render="Label" font="Regular; 20" foregroundColor="#00ffffff" backgroundColor="#00000000" halign="left" transparent="1" />
	<widget source="zoomBtn" position="631,640" size="360,30" render="Label" font="Regular; 20" foregroundColor="#00ffffff" backgroundColor="#00000000" halign="left" transparent="1" />
	<eLabel position="55,635" size="5,40" backgroundColor="#00e61700" />
	<eLabel position="242,635" size="5,40" backgroundColor="#0061e500" />
	<eLabel position="430,635" size="5,40" backgroundColor="#00e5dd00" />
	<eLabel position="616,635" size="5,40" backgroundColor="#000064c7" />
	<widget name="helperimage" position="840,222" size="256,256" backgroundColor="#00000000" zPosition="1" transparent="1" alphatest="blend" />
	<widget name="helpertext" position="800,490" size="336,160" font="Regular; 18" backgroundColor="#00000000" foregroundColor="#00ffffff" halign="center" valign="center" transparent="1"/>
	</screen>
"""

    def __init__(self, session, args=None):
        Screen.__init__(self, session)
        self.session = session
        self.Scale = AVSwitch().getFramebufferScale()
        self.PicLoad = ePicLoad()
        self["helperimage"] = Pixmap()
        self["helpertext"] = Label()

        self["titleText"] = StaticText("")
        self["titleText"].setText(_("Skinpart settings"))

        self["cancelBtn"] = StaticText("")
        self["cancelBtn"].setText(_("Cancel"))

        self["saveBtn"] = StaticText("")
        self["saveBtn"].setText(_("Save"))

        self["defaultsBtn"] = StaticText("")
        self["defaultsBtn"].setText(_("Defaults"))

        self["zoomBtn"] = StaticText("")
        self["zoomBtn"].setText(_("Zoom"))

        self.linkGlobalSkinParts()
        self.getSkinParts()

        ConfigListScreen.__init__(self,
                                  self.getMenuItemList(),
                                  session=session,
                                  on_change=self.selectionChanged)

        self["actions"] = ActionMap(
            [
                "OkCancelActions", "DirectionActions", "InputActions",
                "ColorActions"
            ], {
                "left": self.keyLeft,
                "down": self.keyDown,
                "up": self.keyUp,
                "right": self.keyRight,
                "red": self.exit,
                "green": self.save,
                "blue": self.zoom,
                "yellow": self.defaults,
                "cancel": self.exit
            }, -1)

        self.onLayoutFinish.append(self.UpdatePicture)

    def selectionChanged(self):
        cur = self["config"].getCurrent()
        cur = cur and len(cur) > 3 and cur[3]

        if cur == "ENABLED":
            self["config"].setList(self.getMenuItemList())

    def getMenuItemList(self):
        list = []
        char = 150
        tab = " " * 10
        sep = "-"
        nodesc = _("No description available.")
        noprev = _("\n(No preview picture available.)")

        section = _("/usr/share/enigma2/MetrixHD/skinparts/[part]/[part].xml")
        list.append(
            getConfigListEntry(
                section + tab + sep * (char - len(section) - len(tab)), ))
        pidx = 0
        for part in self.partlist:
            if not path.isfile(self.parts[pidx][0][0] +
                               self.parts[pidx][0][1] + '.xml'):
                part.value = '0'
                itext = _("Skinpart are not available - can't be activated.")
            else:
                if not self.parts[pidx][0][3]:
                    itext = nodesc
                else:
                    itext = self.parts[pidx][0][3]
                if not self.parts[pidx][0][2]:
                    itext += noprev
            preview = self.parts[pidx][0][0] + self.parts[pidx][0][2]
            list.append(
                getConfigListEntry(tab + self.parts[pidx][0][1], part, itext,
                                   'ENABLED', preview))
            if int(part.value) > 1:
                sidx = 0
                for screen in self.screenlist[pidx]:
                    if not self.screens[pidx][sidx][3]:
                        itext = nodesc
                    else:
                        itext = self.screens[pidx][sidx][3]
                    if not self.screens[pidx][sidx][2]:
                        itext += noprev
                    preview = self.parts[pidx][0][0] + '/' + self.screens[
                        pidx][sidx][2]
                    list.append(
                        getConfigListEntry(
                            tab * 2 + self.screens[pidx][sidx][1], screen,
                            itext, 'ENABLED', preview))
                    sidx += 1
            pidx += 1

        return list

    def linkGlobalSkinParts(self):
        from os import symlink, makedirs
        dir_global_skinparts = "/usr/share/enigma2/skinparts"
        dir_local_skinparts = "/usr/share/enigma2/MetrixHD/skinparts"
        if path.exists(dir_global_skinparts):
            for pack in listdir(dir_global_skinparts):
                if path.isdir(dir_global_skinparts + "/" + pack):
                    for d in listdir(dir_global_skinparts + "/" + pack):
                        if path.exists(dir_global_skinparts + "/" + pack +
                                       "/" + d + "/" + d + ".xml"):
                            if not path.exists(dir_local_skinparts + "/" + d):
                                makedirs(dir_local_skinparts + "/" + d)
                            for f in listdir(dir_global_skinparts + "/" +
                                             pack + "/" + d):
                                print dir_local_skinparts + "/" + d + "/" + f
                                print dir_global_skinparts + "/" + pack + "/" + d + "/" + f
                                if (not path.islink(dir_local_skinparts + "/" +
                                                    d + "/" + f)
                                    ) and (
                                        not path.exists(dir_local_skinparts +
                                                        "/" + d + "/" + f)):
                                    print "1"
                                    symlink(
                                        dir_global_skinparts + "/" + pack +
                                        "/" + d + "/" + f,
                                        dir_local_skinparts + "/" + d + "/" +
                                        f)

    def getSkinParts(self):
        self.parts = {}
        self.screens = {}
        self.partlist = ConfigSubList()
        self.screenlist = ConfigSubDict()
        self.idx = 0
        self.readSkinParts("/usr/share/enigma2/MetrixHD/skinparts/")

    def readSkinParts(self, skinpartdir):
        for skinpart in listdir(skinpartdir):
            enabled = '0'
            partname = skinpart
            partpath = skinpartdir + skinpart + '/'
            partfile = partpath + skinpart + '.xml'
            if not path.isfile(partpath[:-1]):
                if path.isfile(partpath + 'enabled'):
                    enabled = '1'
                self.readSkinPartScreens(partpath, partname)
                if len(self.screenlist[self.idx]):
                    self.partlist.append(
                        ConfigSelection(default='0',
                                        choices=[("0", _("No")),
                                                 ("2", _("Yes, show screens")),
                                                 ("1", _("Yes")),
                                                 ("3", _("Yes, show screens"))
                                                 ]))
                else:
                    self.partlist.append(
                        ConfigSelection(default='0',
                                        choices=[("0", _("No")),
                                                 ("1", _("Yes"))]))
                self.partlist[self.idx].value = enabled
                self.idx += 1

    def readSkinPartScreens(self, partpath, partname):
        part = []
        screen = []
        lines = []
        self.screenlist[self.idx] = ConfigSubList()

        lidx = screenname = previewfile = description = ''
        enabled = p_nfo = s_nfo = False

        if path.isfile(partpath + partname + '.xml'):
            f = open(partpath + partname + '.xml', 'r')
            lines = f.readlines()
            f.close()
            if path.isfile(partpath + partname + '.txt'):
                f = open(partpath + partname + '.txt', 'r')
                description = f.read()
                f.close()
            if path.isfile(partpath + partname + '.png'):
                previewfile = partname + '.png'
            elif path.isfile(partpath + partname + '.jpg'):
                previewfile = partname + '.jpg'

        idx = 0
        for line in lines:
            idx += 1
            if '<screen' in line or '</screen>' in line:
                if p_nfo:
                    description = description.replace(
                        '\t', '').lstrip('\n').rstrip('\n').strip()
                    part.append((partpath, partname, previewfile, description))
                    previewfile = description = ''
                    p_nfo = False
                elif s_nfo:
                    description = description.replace(
                        '\t', '').lstrip('\n').rstrip('\n').strip()
                    screen.append((lidx, screenname, previewfile,
                                   description.rstrip('\n'), enabled))
                    lidx = screenname = previewfile = description = ''
                    enabled = s_nfo = False

            if '<skin>' in line:
                p_nfo = True
            if '<screen' in line and not '#hide#' in line:
                s_nfo = True
                a = line.find('name=')
                b = line.find('"', a)
                c = line.find('"', b + 1)
                name = line[b + 1:c]
                #// fix old typo
                name = name.replace('#deactivatd#', '#deactivated#')
                #//
                sname = name.replace('#deactivated#', '')
                if path.isfile(partpath + sname + '.txt'):
                    f = open(partpath + sname + '.txt', 'r')
                    description = f.read()
                    f.close()
                if path.isfile(partpath + sname + '.png'):
                    previewfile = sname + '.png'
                elif path.isfile(partpath + sname + '.jpg'):
                    previewfile = sname + '.jpg'

                if '#deactivated#' in name:
                    screenname = name.replace('#deactivated#', '')
                    enabled = False
                else:
                    screenname = name
                    enabled = True
                lidx = idx

            if '#description#' in line:
                a = line.find('#description#')
                description += line[a + 13:]
            elif '#previewfile#' in line:
                a = line.find('#previewfile#')
                file = line[a + 13:].replace('\n', '').replace(
                    '\t', '').lstrip('/').strip()
                if path.isfile(partpath + file):
                    previewfile = file

        if not part:
            part.append((partpath, partname, previewfile, description))
        self.parts[self.idx] = part
        self.screens[self.idx] = screen

        idx = 0
        for screen in self.screens[self.idx]:
            self.screenlist[self.idx].append(ConfigYesNo(default=False))
            self.screenlist[self.idx][idx].value = self.screens[self.idx][idx][
                4]  #screen[4]
            idx += 1

    def GetPicturePath(self):
        zoomEnable = False
        if len(self["config"].getCurrent()) > 3:
            picturepath = self["config"].getCurrent()[4]
            if path.isfile(picturepath):
                zoomEnable = True
        if not zoomEnable or not path.isfile(picturepath):
            picturepath = resolveFilename(
                SCOPE_CURRENT_SKIN, "mymetrixlite/MyMetrixLiteSkinpart.png")
            if not fileExists(picturepath):
                picturepath = MAIN_IMAGE_PATH % "MyMetrixLiteSkinpart"

        if zoomEnable and not "blue" in self["actions"].actions:
            self["actions"].actions.update({"blue": self.zoom})
            self["zoomBtn"].setText(_("Zoom"))
        elif not zoomEnable and "blue" in self["actions"].actions:
            del self["actions"].actions["blue"]
            self["zoomBtn"].setText(_(" "))

        return picturepath

    def UpdatePicture(self):
        self.PicLoad.PictureData.get().append(self.DecodePicture)
        self.onLayoutFinish.append(self.ShowPicture)

    def ShowPicture(self):
        self.PicLoad.setPara([
            self["helperimage"].instance.size().width(),
            self["helperimage"].instance.size().height(), self.Scale[0],
            self.Scale[1], 0, 1, "#00000000"
        ])
        self.PicLoad.startDecode(self.GetPicturePath())
        self.showHelperText()

    def DecodePicture(self, PicInfo=""):
        ptr = self.PicLoad.getData()
        self["helperimage"].instance.setPixmap(ptr)

    def keyLeft(self):
        ConfigListScreen.keyLeft(self)
        #self.ShowPicture()

    def keyRight(self):
        ConfigListScreen.keyRight(self)
        #self.ShowPicture()

    def keyDown(self):
        self["config"].instance.moveSelection(self["config"].instance.moveDown)
        self.ShowPicture()

    def keyUp(self):
        self["config"].instance.moveSelection(self["config"].instance.moveUp)
        self.ShowPicture()

    def showInfo(self):
        self.session.open(MessageBox, _("Information"), MessageBox.TYPE_INFO)

    def zoom(self):
        self.session.open(zoomPreview, self.GetPicturePath())

    def save(self):
        idxerrtxt = ''
        idxerrcnt = 0
        pidx = 0
        for part in self.partlist:
            idxerr = False
            efile = self.parts[pidx][0][0] + 'enabled'
            sfile = self.parts[pidx][0][0] + self.parts[pidx][0][1] + '.xml'
            tfile = self.parts[pidx][0][0] + self.parts[pidx][0][1] + '.xml.tmp'
            if part.value != '0':
                f = open(efile, 'w').close()
                if path.isfile(sfile):
                    f = open(sfile, 'r')
                    source = f.readlines()
                    f.close()
                    sidx = 0
                    for screen in self.screenlist[pidx]:
                        idx = self.screens[pidx][sidx][0] - 1
                        if len(source) > idx:
                            line = source[idx]
                            screenname = ''
                            if '<screen' in line:
                                a = line.find('name=')
                                b = line.find('"', a)
                                c = line.find('"', b + 1)
                                name = line[b + 1:c]
                                #// fix old typo
                                if '#deactivatd#' in name:
                                    screenname = name = name.replace(
                                        '#deactivatd#', '#deactivated#')
                                #//
                                if name.replace(
                                        '#deactivated#',
                                        '') == self.screens[pidx][sidx][1]:
                                    if not screen.value and not '#deactivated#' in name:
                                        screenname = '#deactivated#' + name
                                    elif screen.value and '#deactivated#' in name:
                                        screenname = name.replace(
                                            '#deactivated#', '')
                                    if screenname:
                                        line = line[:b +
                                                    1] + screenname + line[c:]
                                        source[idx] = line
                                else:
                                    idxerr = True
                                    if idxerrcnt:
                                        idxerrtxt += '\n'
                                    idxerrcnt += 1
                                    idxerrtxt += '%d. name error - file: %s, line: %s, screen: %s (%s)' % (
                                        idxerrcnt, self.parts[pidx][0][1] +
                                        '.xml', self.screens[pidx][sidx][0],
                                        self.screens[pidx][sidx][1], name)
                                    break
                            else:
                                idxerr = True
                                if idxerrcnt:
                                    idxerrtxt += '\n'
                                idxerrcnt += 1
                                idxerrtxt += '%d. index error - file: %s, line: %s, screen: %s' % (
                                    idxerrcnt, self.parts[pidx][0][1] + '.xml',
                                    self.screens[pidx][sidx][0],
                                    self.screens[pidx][sidx][1])
                                break
                        else:
                            idxerr = True
                            if idxerrcnt:
                                idxerrtxt += '\n'
                            idxerrcnt += 1
                            idxerrtxt += '%d. file error - file: %s (index > lines)\n' % (
                                sfile)
                            break
                        sidx += 1
                    if not idxerr:
                        f = open(tfile, 'w')
                        f.writelines(source)
                        f.close()
            else:
                if path.isfile(efile):
                    remove(efile)
            if not idxerr and path.isfile(tfile) and path.isfile(sfile):
                copy(tfile, sfile)
                remove(tfile)
            pidx += 1

        if idxerrcnt:
            self.session.open(MessageBox, idxerrtxt, MessageBox.TYPE_ERROR)
            self.exit()

        for x in self["config"].list:
            if len(x) > 1:
                x[1].save()

        configfile.save()
        self.exit()

    def exit(self):
        for x in self["config"].list:
            if len(x) > 1:
                x[1].cancel()

        self.close()

    def defaults(self):
        for x in self["config"].list:
            if len(x) > 1:
                self.setInputToDefault(x[1])
                x[1].save()
        if self.session:
            self["config"].setList(self.getMenuItemList())
            self.ShowPicture()
        else:
            configfile.save()

    def setNewValue(self, configItem, newValue):
        configItem.setValue(newValue)

    def setInputToDefault(self, configItem):
        configItem.setValue(configItem.default)

    def showHelperText(self):
        cur = self["config"].getCurrent()
        if cur and len(cur) > 2 and cur[2] and cur[2] != _("helptext"):
            self["helpertext"].setText(cur[2])
        else:
            self["helpertext"].setText(" ")
class TimerEntry(Screen, ConfigListScreen):
    def __init__(self, session, timer):
        Screen.__init__(self, session)
        self.timer = timer

        self.entryDate = None
        self.entryService = None

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

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

        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,
                "up": self.keyUp,
                "down": self.keyDown,
            },
            -2,
        )

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

    def createConfig(self):
        afterevent = {
            AFTEREVENT.NONE: "nothing",
            AFTEREVENT.WAKEUP: "wakeup",
            AFTEREVENT.WAKEUPTOSTANDBY: "wakeuptostandby",
            AFTEREVENT.STANDBY: "standby",
            AFTEREVENT.DEEPSTANDBY: "deepstandby",
        }[self.timer.afterEvent]

        timertype = {
            TIMERTYPE.NONE: "nothing",
            TIMERTYPE.WAKEUP: "wakeup",
            TIMERTYPE.WAKEUPTOSTANDBY: "wakeuptostandby",
            TIMERTYPE.AUTOSTANDBY: "autostandby",
            TIMERTYPE.AUTODEEPSTANDBY: "autodeepstandby",
            TIMERTYPE.STANDBY: "standby",
            TIMERTYPE.DEEPSTANDBY: "deepstandby",
            TIMERTYPE.REBOOT: "reboot",
            TIMERTYPE.RESTART: "restart",
        }[self.timer.timerType]

        weekday_table = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
        time_table = [
            (1, "1"),
            (3, "3"),
            (5, "5"),
            (10, "10"),
            (15, "15"),
            (30, "30"),
            (45, "45"),
            (60, "60"),
            (75, "75"),
            (90, "90"),
            (105, "105"),
            (120, "120"),
            (135, "135"),
            (150, "150"),
            (165, "165"),
            (180, "180"),
            (195, "195"),
            (210, "210"),
            (225, "225"),
            (240, "240"),
            (255, "255"),
            (270, "270"),
            (285, "285"),
            (300, "300"),
        ]
        traffic_table = [(10, "10"), (50, "50"), (100, "100"), (500, "500"), (1000, "1000")]

        # 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

        if SystemInfo["DeepstandbySupport"]:
            shutdownString = _("go to deep standby")
        else:
            shutdownString = _("shut down")
        self.timerentry_timertype = ConfigSelection(
            choices=[
                ("nothing", _("do nothing")),
                ("wakeup", _("wakeup")),
                ("wakeuptostandby", _("wakeup to standby")),
                ("autostandby", _("auto standby")),
                ("autodeepstandby", _("auto deepstandby")),
                ("standby", _("go to standby")),
                ("deepstandby", shutdownString),
                ("reboot", _("reboot system")),
                ("restart", _("restart GUI")),
            ],
            default=timertype,
        )
        self.timerentry_afterevent = ConfigSelection(
            choices=[
                ("nothing", _("do nothing")),
                ("wakeup", _("wakeup")),
                ("wakeuptostandby", _("wakeup to standby")),
                ("standby", _("go to standby")),
                ("deepstandby", shutdownString),
                ("nothing", _("do nothing")),
            ],
            default=afterevent,
        )
        self.timerentry_type = ConfigSelection(choices=[("once", _("once")), ("repeated", _("repeated"))], default=type)

        self.timerentry_repeated = ConfigSelection(
            default=repeated,
            choices=[
                ("daily", _("daily")),
                ("weekly", _("weekly")),
                ("weekdays", _("Mon-Fri")),
                ("user", _("user defined")),
            ],
        )
        self.timerrntry_autosleepdelay = ConfigSelection(choices=time_table, default=self.timer.autosleepdelay)
        self.timerentry_autosleeprepeat = ConfigSelection(
            choices=[("once", _("once")), ("repeated", _("repeated"))], default=self.timer.autosleeprepeat
        )
        self.timerrntry_autosleepinstandbyonly = ConfigSelection(
            choices=[("yes", _("only in Standby")), ("no", _("Standard (always)")), ("noquery", _("without Query"))],
            default=self.timer.autosleepinstandbyonly,
        )
        self.timerrntry_autosleepwindow = ConfigSelection(
            choices=[("yes", _("Yes")), ("no", _("No"))], default=self.timer.autosleepwindow
        )
        self.timerrntry_autosleepbegin = ConfigClock(default=self.timer.autosleepbegin)
        self.timerrntry_autosleepend = ConfigClock(default=self.timer.autosleepend)

        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) / 60) > 4), choices=[(True, _("yes")), (False, _("no"))]
        )

        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]))

        self.timerrntry_showExtended = ConfigSelection(
            default=(self.timer.nettraffic == "yes" or self.timer.netip == "yes"),
            choices=[(True, _("yes")), (False, _("no"))],
        )
        self.timerrntry_nettraffic = ConfigSelection(
            choices=[("yes", _("Yes")), ("no", _("No"))], default=self.timer.nettraffic
        )
        self.timerrntry_trafficlimit = ConfigSelection(choices=traffic_table, default=self.timer.trafficlimit)
        self.timerrntry_netip = ConfigSelection(choices=[("yes", _("Yes")), ("no", _("No"))], default=self.timer.netip)
        self.timerrntry_ipadress = self.timer.ipadress.split(",")
        self.ipcount = ConfigSelectionNumber(default=len(self.timerrntry_ipadress), stepwidth=1, min=1, max=5)
        self.ipadressEntry = ConfigSubList()
        for x in (0, 1, 2, 3, 4, 5):
            try:
                self.ipadressEntry.append(
                    ConfigIP(default=[int(n) for n in self.timerrntry_ipadress[x].split(".")] or [0, 0, 0, 0])
                )
            except:
                self.ipadressEntry.append(ConfigIP(default=[0, 0, 0, 0]))

    def createSetup(self, widget):
        self.list = []
        self.timerType = getConfigListEntry(_("Timer type"), self.timerentry_timertype)
        self.list.append(self.timerType)

        self.timerTypeEntry = getConfigListEntry(_("Repeat type"), self.timerentry_type)
        self.entryStartTime = getConfigListEntry(_("Start time"), self.timerentry_starttime)
        self.entryShowEndTime = getConfigListEntry(_("Set end time"), self.timerentry_showendtime)
        self.entryEndTime = getConfigListEntry(_("End time"), self.timerentry_endtime)
        self.frequencyEntry = getConfigListEntry(_("Repeats"), self.timerentry_repeated)
        self.entryDate = getConfigListEntry(_("Date"), self.timerentry_date)
        self.repeatedbegindateEntry = getConfigListEntry(_("Starting on"), self.timerentry_repeatedbegindate)
        self.autosleepwindowEntry = getConfigListEntry(
            _("Restrict the active time range"), self.timerrntry_autosleepwindow
        )
        self.netExtendedEntry = getConfigListEntry(_("Show advanced settings"), self.timerrntry_showExtended)
        self.nettrafficEntry = getConfigListEntry(_("Enable Network Traffic check"), self.timerrntry_nettraffic)
        self.netipEntry = getConfigListEntry(_("Enable Network IP address check"), self.timerrntry_netip)
        self.ipcountEntry = getConfigListEntry(_("Select of the number"), self.ipcount)

        if self.timerentry_timertype.value == "autostandby" or self.timerentry_timertype.value == "autodeepstandby":
            if self.timerentry_timertype.value == "autodeepstandby":
                self.list.append(
                    getConfigListEntry(
                        _("Execution condition"),
                        self.timerrntry_autosleepinstandbyonly,
                        _(
                            "The setting 'without query' is the same as 'standard' without additional confirmation query. All other dependencies (e.g. recordings, time range) stay persist."
                        ),
                    )
                )
            self.list.append(getConfigListEntry(_("Sleep delay"), self.timerrntry_autosleepdelay))
            self.list.append(getConfigListEntry(_("Repeat type"), self.timerentry_autosleeprepeat))

            self.list.append(self.autosleepwindowEntry)
            if self.timerrntry_autosleepwindow.value == "yes":
                self.list.append(getConfigListEntry(_("Start time"), self.timerrntry_autosleepbegin))
                self.list.append(getConfigListEntry(_("End time"), self.timerrntry_autosleepend))

            if self.timerentry_timertype.value == "autodeepstandby":
                self.list.append(self.netExtendedEntry)
                if self.timerrntry_showExtended.value:
                    self.list.append(self.nettrafficEntry)
                    if self.timerrntry_nettraffic.value == "yes":
                        self.list.append(
                            getConfigListEntry(
                                _("Lower limit in kilobits per seconds [kbit/s]"), self.timerrntry_trafficlimit
                            )
                        )

                    self.list.append(self.netipEntry)
                    if self.timerrntry_netip.value == "yes":
                        self.list.append(self.ipcountEntry)
                        for x in range(0, self.ipcount.value):
                            self.list.append(
                                getConfigListEntry(("%d. " + _("IP address")) % (x + 1), self.ipadressEntry[x])
                            )

        else:
            self.list.append(self.timerTypeEntry)

            if self.timerentry_type.value == "once":
                self.frequencyEntry = None
            else:  # repeated
                self.list.append(self.frequencyEntry)
                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_type.value == "once":
                self.list.append(self.entryDate)

            self.list.append(self.entryStartTime)
            self.list.append(self.entryShowEndTime)

            if self.timerentry_showendtime.value:
                self.list.append(self.entryEndTime)
                self.list.append(getConfigListEntry(_("After event"), self.timerentry_afterevent))

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

    def createSummary(self):
        pass

    def checkSummary(self):
        # self["summary_description"].text = self["config"].getCurrent()[0]
        if len(self["config"].getCurrent()) > 2 and self["config"].getCurrent()[2]:
            self["description"].setText(self["config"].getCurrent()[2])
        else:
            self["description"].setText("")

    def newConfig(self):
        if self["config"].getCurrent() in (
            self.timerType,
            self.timerTypeEntry,
            self.frequencyEntry,
            self.entryShowEndTime,
            self.autosleepwindowEntry,
            self.netExtendedEntry,
            self.nettrafficEntry,
            self.netipEntry,
            self.ipcountEntry,
        ):
            self.createSetup("config")

    def keyLeft(self):
        ConfigListScreen.keyLeft(self)
        self.newConfig()

    def keyRight(self):
        ConfigListScreen.keyRight(self)
        self.newConfig()

    def keySelect(self):
        cur = self["config"].getCurrent()
        self.keyGo()

    def keyUp(self):
        self["config"].moveUp()
        self.checkSummary()

    def keyDown(self):
        self["config"].moveDown()
        self.checkSummary()

    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, result=None):
        if not self.timerentry_showendtime.value:
            self.timerentry_endtime.value = self.timerentry_starttime.value

        self.timer.resetRepeated()

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

        if self.timerentry_timertype.value == "autostandby" or self.timerentry_timertype.value == "autodeepstandby":
            self.timer.begin = int(time()) + 10
            self.timer.end = self.timer.begin
            self.timer.autosleepinstandbyonly = self.timerrntry_autosleepinstandbyonly.value
            self.timer.autosleepdelay = self.timerrntry_autosleepdelay.value
            self.timer.autosleeprepeat = self.timerentry_autosleeprepeat.value
            self.timerentry_showendtime.value = False
        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

        endaction = self.timerentry_showendtime.value
        if (self.timer.end - self.timer.begin) / 60 < 5 or self.timerentry_showendtime.value is False:
            self.timerentry_afterevent.value = "nothing"
            self.timer.end = self.timer.begin
            if endaction:
                self.session.open(
                    MessageBox,
                    _(
                        "Difference between timer begin and end must be equal or greater than %d minutes.\nEnd Action was disabled !"
                    )
                    % 5,
                    MessageBox.TYPE_INFO,
                    timeout=30,
                )

        self.timer.timerType = {
            "nothing": TIMERTYPE.NONE,
            "wakeup": TIMERTYPE.WAKEUP,
            "wakeuptostandby": TIMERTYPE.WAKEUPTOSTANDBY,
            "autostandby": TIMERTYPE.AUTOSTANDBY,
            "autodeepstandby": TIMERTYPE.AUTODEEPSTANDBY,
            "standby": TIMERTYPE.STANDBY,
            "deepstandby": TIMERTYPE.DEEPSTANDBY,
            "reboot": TIMERTYPE.REBOOT,
            "restart": TIMERTYPE.RESTART,
        }[self.timerentry_timertype.value]

        self.timer.afterEvent = {
            "nothing": AFTEREVENT.NONE,
            "wakeup": AFTEREVENT.WAKEUP,
            "wakeuptostandby": AFTEREVENT.WAKEUPTOSTANDBY,
            "standby": AFTEREVENT.STANDBY,
            "deepstandby": AFTEREVENT.DEEPSTANDBY,
        }[self.timerentry_afterevent.value]

        self.timer.autosleepwindow = self.timerrntry_autosleepwindow.value
        self.timer.autosleepbegin = self.getTimestamp(time(), self.timerrntry_autosleepbegin.value)
        self.timer.autosleepend = self.getTimestamp(time(), self.timerrntry_autosleepend.value)

        self.timer.nettraffic = self.timerrntry_nettraffic.value
        self.timer.trafficlimit = self.timerrntry_trafficlimit.value
        self.timer.netip = self.timerrntry_netip.value
        self.timer.ipadress = "%d.%d.%d.%d" % (
            self.ipadressEntry[0].value[0],
            self.ipadressEntry[0].value[1],
            self.ipadressEntry[0].value[2],
            self.ipadressEntry[0].value[3],
        )
        for x in range(1, self.ipcount.value):
            self.timer.ipadress += ",%d.%d.%d.%d" % (
                self.ipadressEntry[x].value[0],
                self.ipadressEntry[x].value[1],
                self.ipadressEntry[x].value[2],
                self.ipadressEntry[x].value[3],
            )

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

    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 saveTimer(self):
        self.session.nav.PowerTimer.saveTimer()

    def keyCancel(self):
        self.close((False,))
Example #36
0
from Components.ScrollLabel import ScrollLabel
from Components.Pixmap import Pixmap
from enigma import eTimer, eListboxPythonMultiContent, getDesktop, gFont, loadPNG
from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest
from Screens.MessageBox import MessageBox
from Screens.Console import Console
import urllib
from Components.Label import Label
from Components.ServiceEventTracker import ServiceEventTracker
from enigma import iPlayableService, iServiceInformation, eServiceReference, eListboxPythonMultiContent, getDesktop, gFont, loadPNG
from Tools.LoadPixmap import LoadPixmap
from Components.ConfigList import ConfigList, ConfigListScreen
from Components.config import config, ConfigDirectory, ConfigSubsection, ConfigSubList, ConfigEnableDisable, ConfigNumber, ConfigText, ConfigSelection, ConfigYesNo, ConfigPassword, getConfigListEntry, configfile

config.plugins.Cradio = ConfigSubsection()
config.plugins.Cradio.stations = ConfigSubList()
config.plugins.Cradio.stations_count = ConfigNumber(default=0)
currversion = '3.0'
currxmlversion = '3.0'


def initProfileConfig():
    s = ConfigSubsection()
    s.name = ConfigText(default='')
    s.code = ConfigText(default='')
    config.plugins.Cradio.stations.append(s)
    return s


def initConfig():
    count = config.plugins.Cradio.stations_count.value
Example #37
0
	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 = _("%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 = 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 = _("%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])
		self.createSetup("config")
Example #38
0
File: Ci.py Project: wedebe/enigma2
def InitCiConfig():
    config.ci = ConfigSubList()
    config.cimisc = ConfigSubsection()
    for slot in list(range(MAX_NUM_CI)):
        config.ci.append(ConfigSubsection())
        config.ci[slot].canDescrambleMultipleServices = ConfigSelection(
            choices=[("auto", _("Auto")), ("no", _("No")), ("yes", _("Yes"))],
            default="auto")
        config.ci[slot].use_static_pin = ConfigYesNo(default=True)
        config.ci[slot].static_pin = ConfigPIN(default=0)
        config.ci[slot].show_ci_messages = ConfigYesNo(default=True)
        if BoxInfo.getItem("CommonInterfaceSupportsHighBitrates"):
            if getBrandOEM() in ('dags', 'blackbox'):
                config.ci[slot].canHandleHighBitrates = ConfigYesNo(
                    default=True)
            else:
                config.ci[slot].canHandleHighBitrates = ConfigYesNo(
                    default=False)
            config.ci[slot].canHandleHighBitrates.slotid = slot
            config.ci[slot].canHandleHighBitrates.addNotifier(setCIBitrate)
        if BoxInfo.getItem("RelevantPidsRoutingSupport"):
            global relevantPidsRoutingChoices
            if not relevantPidsRoutingChoices:
                relevantPidsRoutingChoices = [("no", _("No")),
                                              ("yes", _("Yes"))]
                default = "no"
                fileName = "/proc/stb/tsmux/ci%d_relevant_pids_routing_choices"
            if fileExists(fileName, 'r'):
                relevantPidsRoutingChoices = []
                fd = open(fileName, 'r')
                data = fd.read()
                data = data.split()
                for x in data:
                    relevantPidsRoutingChoices.append((x, _(x)))
                if default not in data:
                    default = data[0]
            config.ci[slot].relevantPidsRouting = ConfigSelection(
                choices=relevantPidsRoutingChoices, default=default)
            config.ci[slot].relevantPidsRouting.slotid = slot
            config.ci[slot].relevantPidsRouting.addNotifier(
                setRelevantPidsRouting)
    if BoxInfo.getItem("CommonInterfaceCIDelay"):
        config.cimisc.dvbCiDelay = ConfigSelection(default="256",
                                                   choices=[("16", _("16")),
                                                            ("32", _("32")),
                                                            ("64", _("64")),
                                                            ("128", _("128")),
                                                            ("256", _("256"))])
        config.cimisc.dvbCiDelay.addNotifier(setdvbCiDelay)
    if getBrandOEM() in ('entwopia', 'tripledot', 'dreambox'):
        if BoxInfo.getItem("HaveCISSL"):
            config.cimisc.civersion = ConfigSelection(
                default="ciplus1",
                choices=[("auto", _("Auto")), ("ciplus1", _("CI Plus 1.2")),
                         ("ciplus2", _("CI Plus 1.3")),
                         ("legacy", _("CI Legacy"))])
        else:
            config.cimisc.civersion = ConfigSelection(default="legacy",
                                                      choices=[("legacy",
                                                                _("CI Legacy"))
                                                               ])
    else:
        config.cimisc.civersion = ConfigSelection(default="auto",
                                                  choices=[("auto", _("Auto")),
                                                           ("ciplus1",
                                                            _("CI Plus 1.2")),
                                                           ("ciplus2",
                                                            _("CI Plus 1.3")),
                                                           ("legacy",
                                                            _("CI Legacy"))])
from urllib import quote
from urllib import quote as urllib_quote
from Components.Pixmap import Pixmap
from GlobalFunctions import Showiframe
from enigma import eListboxPythonMultiContent, gFont, RT_HALIGN_LEFT, RT_VALIGN_CENTER, ePicLoad, eEnv
from Tools.Directories import fileExists, pathExists
from Components.AVSwitch import AVSwitch
from Components.config import ConfigSubsection, getConfigListEntry, ConfigText, ConfigSelection, ConfigSubList, configfile, ConfigInteger, config
from Components.ConfigList import ConfigList, ConfigListScreen
import time
import os
import commands

config.plugins.mc_wi = ConfigSubsection()
config.plugins.mc_wi.entrycount = ConfigInteger(0)
config.plugins.mc_wi.Entry = ConfigSubList()


def initWeatherPluginEntryConfig():
    s = ConfigSubsection()
    s.city = ConfigText(default="Berlin", visible_width=100, fixed_size=False)
    s.degreetype = ConfigSelection(choices=[("C", _("metric system")),
                                            ("F", _("imperial system"))],
                                   default="C")
    s.weatherlocationcode = ConfigText(default="",
                                       visible_width=100,
                                       fixed_size=False)
    config.plugins.mc_wi.Entry.append(s)
    return s

Example #40
0
	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])
Example #41
0
from Components.PluginComponent import plugins

# Initialize Configuration
config.plugins.simpleRSS = ConfigSubsection()
simpleRSS = config.plugins.simpleRSS
simpleRSS.update_notification = ConfigSelection(choices=[
    ("notification", _("Notification")), ("preview", _("Preview")),
    ("ticker", _("Ticker")), ("none", _("none"))
],
                                                default="preview")
simpleRSS.interval = ConfigNumber(default=15)
simpleRSS.feedcount = ConfigNumber(default=0)
simpleRSS.autostart = ConfigEnableDisable(default=False)
simpleRSS.keep_running = ConfigEnableDisable(default=True)
simpleRSS.feed = ConfigSubList()
i = 0
while i < simpleRSS.feedcount.value:
    s = ConfigSubsection()
    s.uri = ConfigText(default="http://", fixed_size=False)
    s.autoupdate = ConfigEnableDisable(default=True)
    simpleRSS.feed.append(s)
    i += 1
    del s
simpleRSS.enable_google_reader = ConfigYesNo(default=False)
simpleRSS.google_username = ConfigText(default="", fixed_size=False)
simpleRSS.google_password = ConfigPassword(default="")

del simpleRSS, i

# Global Poller-Object
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)
Example #43
0
class TimerEntry(Screen, ConfigListScreen):
	def __init__(self, session, timer):
		Screen.__init__(self, session)
		self.timer = timer

		self.entryDate = None
		self.entryService = None

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

		self.createConfig()

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	def tagEditFinished(self, ret):
		if ret is not None:
			self.timerentry_tags = ret
			self.timerentry_tagsset.setChoices([not ret and "None" or " ".join(ret)])
			self["config"].invalidate(self.tagsSet)
Example #44
0
		("6", WEEKDAYS[6]),
	], default="6")
	config.plugins.AdvHdmiCec.Entries[i].begin = ConfigClock(default=int(begin))
	config.plugins.AdvHdmiCec.Entries[i].end = ConfigClock(default=int(end))
	return config.plugins.AdvHdmiCec.Entries[i]


config.plugins.AdvHdmiCec = ConfigSubsection()
config.plugins.AdvHdmiCec.enable = ConfigYesNo(default=False)
config.plugins.AdvHdmiCec.debug = ConfigYesNo(default=False)
config.plugins.AdvHdmiCec.enable_power_on = ConfigYesNo(default=True)
config.plugins.AdvHdmiCec.enable_power_off = ConfigYesNo(default=True)
config.plugins.AdvHdmiCec.disable_after_enigmastart = ConfigYesNo(default=False)
config.plugins.AdvHdmiCec.disable_from_webif = ConfigYesNo(default=False)
config.plugins.AdvHdmiCec.entriescount = ConfigInteger(0)
config.plugins.AdvHdmiCec.Entries = ConfigSubList()
config.plugins.AdvHdmiCec.show_in = ConfigSelection(choices=[
		("system", _("systemmenue")),
		("plugin", _("pluginmenue")),
		("extension", _("extensions")),
	], default="system")
initTimeSpanEntryList()

ADVHDMI_VERSION = "1.4.3"

# HDMI-Hook-Events
# To implement a hook, just instantiate a AdvHdmiCecIF,
# and overwrite the methods before_event and/or after_event

# Events with boolean-return, that means if the CEC-signal has to be send / handled
ADVHDMI_BEFORE_POWERON = "BEFORE_POWERON"
Example #45
0
	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
Example #46
0
    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])
Example #47
0
class SkinpartSettingsView(ConfigListScreen, Screen):
    skin = """
 <screen name="MyMetrixLiteOtherView" position="0,0" size="1280,720" flags="wfNoBorder" backgroundColor="transparent">
    <eLabel name="new eLabel" position="40,40" zPosition="-2" size="1200,640" backgroundColor="#00000000" transparent="0" />
    <widget source="titleText" position="60,55" size="590,50" render="Label" font="Regular; 40" foregroundColor="#00ffffff" backgroundColor="#00000000" valign="center" transparent="1" />
    <widget name="config" position="61,124" size="590,480" backgroundColor="#00000000" foregroundColor="#00ffffff" scrollbarMode="showOnDemand" transparent="1" />
    <widget source="cancelBtn" position="70,640" size="160,30" render="Label" font="Regular; 20" foregroundColor="#00ffffff" backgroundColor="#00000000" halign="left" transparent="1" />
    <widget source="saveBtn" position="257,640" size="160,30" render="Label" font="Regular; 20" foregroundColor="#00ffffff" backgroundColor="#00000000" halign="left" transparent="1" />
    <widget source="defaultsBtn" position="445,640" size="160,30" render="Label" font="Regular; 20" foregroundColor="#00ffffff" backgroundColor="#00000000" halign="left" transparent="1" />
    <widget source="zoomBtn" position="631,640" size="360,30" render="Label" font="Regular; 20" foregroundColor="#00ffffff" backgroundColor="#00000000" halign="left" transparent="1" />
    <eLabel position="55,635" size="5,40" backgroundColor="#00e61700" />
    <eLabel position="242,635" size="5,40" backgroundColor="#0061e500" />
    <eLabel position="430,635" size="5,40" backgroundColor="#00e5dd00" />
    <eLabel position="616,635" size="5,40" backgroundColor="#000064c7" />
    <widget name="helperimage" position="840,222" size="256,256" backgroundColor="#00000000" zPosition="1" transparent="1" alphatest="blend" />
    <widget name="helpertext" position="800,490" size="336,160" font="Regular; 18" backgroundColor="#00000000" foregroundColor="#00ffffff" halign="center" valign="center" transparent="1"/>
  </screen>
"""

    def __init__(self, session, args = None):
        Screen.__init__(self, session)
        self.session = session
        self.Scale = AVSwitch().getFramebufferScale()
        self.PicLoad = ePicLoad()
        self["helperimage"] = Pixmap()
        self["helpertext"] = Label()

        self["titleText"] = StaticText("")
        self["titleText"].setText(_("Skinpart settings"))

        self["cancelBtn"] = StaticText("")
        self["cancelBtn"].setText(_("Cancel"))

        self["saveBtn"] = StaticText("")
        self["saveBtn"].setText(_("Save"))

        self["defaultsBtn"] = StaticText("")
        self["defaultsBtn"].setText(_("Defaults"))

        self["zoomBtn"] = StaticText("")
        self["zoomBtn"].setText(_("Zoom"))

        initOtherConfig()
        self.getSkinParts()

        ConfigListScreen.__init__(
            self,
            self.getMenuItemList(),
            session = session,
            on_change = self.__selectionChanged
        )

        self["actions"] = ActionMap(
        [
            "OkCancelActions",
            "DirectionActions",
            "InputActions",
            "ColorActions"
        ],
        {
            "left": self.keyLeft,
            "down": self.keyDown,
            "up": self.keyUp,
            "right": self.keyRight,
            "red": self.exit,
            "green": self.save,
            "blue": self.zoom,
            "yellow": self.__defaults,
            "cancel": self.exit
        }, -1)

        self.onLayoutFinish.append(self.UpdatePicture)

    def __selectionChanged(self):
        cur = self["config"].getCurrent()
        cur = cur and len(cur) > 3 and cur[3]

        if cur == "ENABLED":
            self["config"].setList(self.getMenuItemList())

    def getMenuItemList(self):
		list = []
		char = 150
		tab = " "*10
		sep = "-"
		nodesc = _("No description available.")
		noprev = _("\n(No preview picture available.)")

		section = _("/usr/share/enigma2/MetrixHD/skinparts/[part]/[part].xml")
		list.append(getConfigListEntry(section + tab + sep*(char-len(section)-len(tab)), ))
		pidx = 0
		for part in self.partlist:
			if not self.screens[pidx]:
				part.value='0'
				if not path.isfile(self.parts[pidx][0][0] + self.parts[pidx][0][2] + 'xml'):
					itext = _("Skinpart are not available - can't be activated.")
				else:
					itext = _("No screens in skinpart are available - can't be activated.")
			else:
				if not self.parts[pidx][0][3]:
					itext = nodesc
				else:
					itext = self.parts[pidx][0][3]
				if not self.parts[pidx][0][2]:
					itext += noprev
			preview = self.parts[pidx][0][0] + self.parts[pidx][0][2]
			list.append(getConfigListEntry(tab + self.parts[pidx][0][1], part, itext, 'ENABLED', preview))
			if int(part.value) > 1:
				sidx = 0
				for screen in self.screenlist[pidx]:
					if not self.screens[pidx][sidx][3]:
						itext = nodesc
					else:
						itext = self.screens[pidx][sidx][3]
					if not self.screens[pidx][sidx][2]:
						itext += noprev
					preview = self.parts[pidx][0][0] + '/' + self.screens[pidx][sidx][2]
					list.append(getConfigListEntry(tab*2 + self.screens[pidx][sidx][1], screen, itext, 'ENABLED', preview))
					sidx += 1
			pidx += 1

		return list

    def getSkinParts(self):
		self.parts = {}
		self.screens = {}
		self.partlist = ConfigSubList()
		self.screenlist = ConfigSubDict()
		self.idx = 0
		self.readSkinParts("/usr/share/enigma2/MetrixHD/skinparts/")

    def readSkinParts(self, skinpartdir):
		for skinpart in listdir(skinpartdir):
			enabled = '0'
			partname = skinpart
			partpath = skinpartdir + skinpart + '/'
			partfile = partpath + skinpart + '.xml'
			if path.isfile(partfile):
				if path.isfile(partpath + 'enabled'):
					enabled = '1'
				self.partlist.append(ConfigSelection(default = '0', choices = [("0", _("No")), ("2", _("Yes, show screens")), ("1", _("Yes")), ("3", _("Yes, show screens"))]))
				self.partlist[self.idx].value = enabled
				self.readSkinPartScreens(partpath, partname)
				self.idx += 1

    def readSkinPartScreens(self, partpath, partname):
		part = []
		screen = []
		lines = []
		self.screenlist[self.idx] = ConfigSubList()

		lidx = screenname = previewfile = description = ''
		enabled = p_nfo = s_nfo = False

		if path.isfile(partpath + partname + '.xml'):
			f = open(partpath + partname + '.xml', 'r')
			lines = f.readlines()
			f.close()
			if path.isfile(partpath + partname + '.txt'):
				f = open(partpath + partname + '.txt', 'r')
				description = f.read()
				f.close()
			if path.isfile(partpath + partname + '.png'):
				previewfile = partname + '.png'
			elif path.isfile(partpath + partname + '.jpg'):
				previewfile = partname + '.jpg'

		idx = 0
		for line in lines:
			idx += 1
			if '<screen' in line or '</screen>' in line:
				if p_nfo:
					description = description.replace('\t','').lstrip('\n').rstrip('\n').strip()
					part.append((partpath, partname, previewfile, description))
					previewfile = description = ''
					p_nfo = False
				elif s_nfo:
					description = description.replace('\t','').lstrip('\n').rstrip('\n').strip()
					screen.append((lidx, screenname, previewfile, description.rstrip('\n'), enabled))
					lidx = screenname = previewfile = description = ''
					enabled = s_nfo = False

			if '<skin>' in line:
				p_nfo = True
			if '<screen' in line and not '#hide#' in line:
				s_nfo = True
				a=line.find('name=')
				b=line.find('"',a)
				c=line.find('"',b+1)
				name = line[b+1:c]

				sname = name.replace('#deactivatd#','')
				if path.isfile(partpath + sname + '.txt'):
					f = open(partpath + sname + '.txt', 'r')
					description = f.read()
					f.close()
				if path.isfile(partpath + sname + '.png'):
					previewfile =sname + '.png'
				elif path.isfile(partpath + sname + '.jpg'):
					previewfile = sname + '.jpg'

				if '#deactivatd#' in name:
					screenname = name.replace('#deactivatd#','')
					enabled = False
				else:
					screenname = name
					enabled = True
				lidx = idx

			if '#description#' in line:
				a=line.find('#description#')
				description += line[a+13:]
			elif '#previewfile#' in line:
				a=line.find('#previewfile#')
				file = line[a+13:].replace('\n','').replace('\t','').lstrip('/').strip()
				if path.isfile(partpath + file):
					previewfile = file

		if not part:
			part.append((partpath, partname, previewfile, description))
		self.parts[self.idx] = part
		self.screens[self.idx] = screen

		idx = 0
		for screen in self.screens[self.idx]:
			self.screenlist[self.idx].append(ConfigYesNo(default=False))
			self.screenlist[self.idx][idx].value = self.screens[self.idx][idx][4] #screen[4]
			idx += 1

    def GetPicturePath(self):
		try:
			zoomEnable = False
			if len(self["config"].getCurrent()) > 3:
				picturepath = self["config"].getCurrent()[4]
				if path.isfile(picturepath):
					zoomEnable = True
			if not zoomEnable or not path.isfile(picturepath):
				picturepath = MAIN_IMAGE_PATH % "MyMetrixLiteSkinpart"
		except:
			picturepath = MAIN_IMAGE_PATH % "MyMetrixLiteSkinpart"

		if zoomEnable and not "blue" in self["actions"].actions:
			self["actions"].actions.update({"blue":self.zoom})
			self["zoomBtn"].setText(_("Zoom"))
		elif not zoomEnable and "blue" in self["actions"].actions:
			del self["actions"].actions["blue"]
			self["zoomBtn"].setText(_(" "))

		return picturepath

    def UpdatePicture(self):
        self.PicLoad.PictureData.get().append(self.DecodePicture)
        self.onLayoutFinish.append(self.ShowPicture)

    def ShowPicture(self):
        self.PicLoad.setPara([self["helperimage"].instance.size().width(),self["helperimage"].instance.size().height(),self.Scale[0],self.Scale[1],0,1,"#00000000"])
        self.PicLoad.startDecode(self.GetPicturePath())
        self.showHelperText()

    def DecodePicture(self, PicInfo = ""):
        ptr = self.PicLoad.getData()
        self["helperimage"].instance.setPixmap(ptr)

    def keyLeft(self):
        ConfigListScreen.keyLeft(self)
        #self.ShowPicture()

    def keyRight(self):
        ConfigListScreen.keyRight(self)
        #self.ShowPicture()

    def keyDown(self):
        self["config"].instance.moveSelection(self["config"].instance.moveDown)
        self.ShowPicture()

    def keyUp(self):
        self["config"].instance.moveSelection(self["config"].instance.moveUp)
        self.ShowPicture()

    def showInfo(self):
        self.session.open(MessageBox, _("Information"), MessageBox.TYPE_INFO)

    def zoom(self):
		self.session.open(zoomPreview, self.GetPicturePath())

    def save(self):
		idxerrtxt = ''
		idxerrcnt = 0
		pidx = 0
		for part in self.partlist:
			idxerr = False
			efile = self.parts[pidx][0][0] + 'enabled'
			sfile = self.parts[pidx][0][0] + self.parts[pidx][0][1] + '.xml'
			tfile = self.parts[pidx][0][0] + self.parts[pidx][0][1] + '.xml.tmp'
			if part.value != '0':
				f = open(efile, 'w').close()
				if path.isfile(sfile):
					f = open(sfile, 'r')
					source = f.readlines()
					f.close()
					sidx = 0
					for screen in self.screenlist[pidx]:
						idx = self.screens[pidx][sidx][0] - 1
						if len(source) > idx:
							line = source[idx]
							screenname = ''
							if '<screen' in line:
								a=line.find('name=')
								b=line.find('"',a)
								c=line.find('"',b+1)
								name = line[b+1:c]
								if name.replace('#deactivatd#','') == self.screens[pidx][sidx][1]:
									if not screen.value and not '#deactivatd#' in name:
										screenname = '#deactivatd#' + name
									elif screen.value and'#deactivatd#' in name:
										screenname = name.replace('#deactivatd#','')
									if screenname:
										line = line[:b+1] + screenname + line[c:]
										source[idx] = line
								else:
									idxerr = True
									if idxerrcnt: idxerrtxt += '\n'
									idxerrcnt += 1
									idxerrtxt += '%d. name error - file: %s, line: %s, screen: %s (%s)' %(idxerrcnt, self.parts[pidx][0][1] + '.xml', self.screens[pidx][sidx][0], self.screens[pidx][sidx][1], name)
									break
							else:
								idxerr = True
								if idxerrcnt: idxerrtxt += '\n'
								idxerrcnt += 1
								idxerrtxt += '%d. index error - file: %s, line: %s, screen: %s' %(idxerrcnt, self.parts[pidx][0][1] + '.xml', self.screens[pidx][sidx][0], self.screens[pidx][sidx][1])
								break
						else:
							idxerr = True
							if idxerrcnt: idxerrtxt += '\n'
							idxerrcnt += 1
							idxerrtxt +=  '%d. file error - file: %s (index > lines)\n' %(sfile)
							break
						sidx += 1
					if not idxerr:
						f = open(tfile, 'w')
						f.writelines(source)
						f.close()
			else:
				if path.isfile(efile):
					remove(efile)
			if not idxerr and path.isfile(tfile) and path.isfile(sfile):
				copy(tfile,sfile)
				remove(tfile)
			pidx += 1

		if idxerrcnt:
			self.session.open(MessageBox, idxerrtxt, MessageBox.TYPE_ERROR)
			self.exit()

		for x in self["config"].list:
			if len(x) > 1:
				x[1].save()

		configfile.save()
		self.exit()

    def exit(self):
        for x in self["config"].list:
            if len(x) > 1:
                    x[1].cancel()

        self.close()

    def defaults(self):
        for x in self["config"].list:
            if len(x) > 1:
                self.setInputToDefault(x[1])
                x[1].save()
        configfile.save()

    def __defaults(self):
        for x in self["config"].list:
            if len(x) > 1:
                self.setInputToDefault(x[1])
        self["config"].setList(self.getMenuItemList())
        self.ShowPicture()
        #self.save()

    def setNewValue(self, configItem, newValue):
        configItem.setValue(newValue)

    def setInputToDefault(self, configItem):
        configItem.setValue(configItem.default)

    def showHelperText(self):
        cur = self["config"].getCurrent()
        if cur and len(cur) > 2 and cur[2] and cur[2] != _("helptext"):
            self["helpertext"].setText(cur[2])
        else:
            self["helpertext"].setText(" ")
    def createConfig(self):
        afterevent = {
            AFTEREVENT.NONE: "nothing",
            AFTEREVENT.WAKEUP: "wakeup",
            AFTEREVENT.WAKEUPTOSTANDBY: "wakeuptostandby",
            AFTEREVENT.STANDBY: "standby",
            AFTEREVENT.DEEPSTANDBY: "deepstandby",
        }[self.timer.afterEvent]

        timertype = {
            TIMERTYPE.NONE: "nothing",
            TIMERTYPE.WAKEUP: "wakeup",
            TIMERTYPE.WAKEUPTOSTANDBY: "wakeuptostandby",
            TIMERTYPE.AUTOSTANDBY: "autostandby",
            TIMERTYPE.AUTODEEPSTANDBY: "autodeepstandby",
            TIMERTYPE.STANDBY: "standby",
            TIMERTYPE.DEEPSTANDBY: "deepstandby",
            TIMERTYPE.REBOOT: "reboot",
            TIMERTYPE.RESTART: "restart",
        }[self.timer.timerType]

        weekday_table = ("mon", "tue", "wed", "thu", "fri", "sat", "sun")
        time_table = [
            (1, "1"),
            (3, "3"),
            (5, "5"),
            (10, "10"),
            (15, "15"),
            (30, "30"),
            (45, "45"),
            (60, "60"),
            (75, "75"),
            (90, "90"),
            (105, "105"),
            (120, "120"),
            (135, "135"),
            (150, "150"),
            (165, "165"),
            (180, "180"),
            (195, "195"),
            (210, "210"),
            (225, "225"),
            (240, "240"),
            (255, "255"),
            (270, "270"),
            (285, "285"),
            (300, "300"),
        ]
        traffic_table = [(10, "10"), (50, "50"), (100, "100"), (500, "500"), (1000, "1000")]

        # 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

        if SystemInfo["DeepstandbySupport"]:
            shutdownString = _("go to deep standby")
        else:
            shutdownString = _("shut down")
        self.timerentry_timertype = ConfigSelection(
            choices=[
                ("nothing", _("do nothing")),
                ("wakeup", _("wakeup")),
                ("wakeuptostandby", _("wakeup to standby")),
                ("autostandby", _("auto standby")),
                ("autodeepstandby", _("auto deepstandby")),
                ("standby", _("go to standby")),
                ("deepstandby", shutdownString),
                ("reboot", _("reboot system")),
                ("restart", _("restart GUI")),
            ],
            default=timertype,
        )
        self.timerentry_afterevent = ConfigSelection(
            choices=[
                ("nothing", _("do nothing")),
                ("wakeup", _("wakeup")),
                ("wakeuptostandby", _("wakeup to standby")),
                ("standby", _("go to standby")),
                ("deepstandby", shutdownString),
                ("nothing", _("do nothing")),
            ],
            default=afterevent,
        )
        self.timerentry_type = ConfigSelection(choices=[("once", _("once")), ("repeated", _("repeated"))], default=type)

        self.timerentry_repeated = ConfigSelection(
            default=repeated,
            choices=[
                ("daily", _("daily")),
                ("weekly", _("weekly")),
                ("weekdays", _("Mon-Fri")),
                ("user", _("user defined")),
            ],
        )
        self.timerrntry_autosleepdelay = ConfigSelection(choices=time_table, default=self.timer.autosleepdelay)
        self.timerentry_autosleeprepeat = ConfigSelection(
            choices=[("once", _("once")), ("repeated", _("repeated"))], default=self.timer.autosleeprepeat
        )
        self.timerrntry_autosleepinstandbyonly = ConfigSelection(
            choices=[("yes", _("only in Standby")), ("no", _("Standard (always)")), ("noquery", _("without Query"))],
            default=self.timer.autosleepinstandbyonly,
        )
        self.timerrntry_autosleepwindow = ConfigSelection(
            choices=[("yes", _("Yes")), ("no", _("No"))], default=self.timer.autosleepwindow
        )
        self.timerrntry_autosleepbegin = ConfigClock(default=self.timer.autosleepbegin)
        self.timerrntry_autosleepend = ConfigClock(default=self.timer.autosleepend)

        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) / 60) > 4), choices=[(True, _("yes")), (False, _("no"))]
        )

        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]))

        self.timerrntry_showExtended = ConfigSelection(
            default=(self.timer.nettraffic == "yes" or self.timer.netip == "yes"),
            choices=[(True, _("yes")), (False, _("no"))],
        )
        self.timerrntry_nettraffic = ConfigSelection(
            choices=[("yes", _("Yes")), ("no", _("No"))], default=self.timer.nettraffic
        )
        self.timerrntry_trafficlimit = ConfigSelection(choices=traffic_table, default=self.timer.trafficlimit)
        self.timerrntry_netip = ConfigSelection(choices=[("yes", _("Yes")), ("no", _("No"))], default=self.timer.netip)
        self.timerrntry_ipadress = self.timer.ipadress.split(",")
        self.ipcount = ConfigSelectionNumber(default=len(self.timerrntry_ipadress), stepwidth=1, min=1, max=5)
        self.ipadressEntry = ConfigSubList()
        for x in (0, 1, 2, 3, 4, 5):
            try:
                self.ipadressEntry.append(
                    ConfigIP(default=[int(n) for n in self.timerrntry_ipadress[x].split(".")] or [0, 0, 0, 0])
                )
            except:
                self.ipadressEntry.append(ConfigIP(default=[0, 0, 0, 0]))
Example #49
0
from Plugins.Extensions.PurePrestige.soupparse import *
from Components.ScrollLabel import ScrollLabel
from twisted.web.client import downloadPage, getPage
import urllib2
from threading import Timer
import re
import sys
from urllib2 import URLError
from enigma import eTimer, eListboxPythonMultiContent, gFont, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_HALIGN_CENTER, getDesktop, loadPNG, loadPic
from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest
from Components.ConfigList import ConfigList, ConfigListScreen
from Components.config import config, ConfigDirectory, ConfigSubsection, ConfigSubList, ConfigEnableDisable, ConfigNumber, ConfigText, ConfigSelection, ConfigYesNo, ConfigPassword, getConfigListEntry, configfile
from Tools.Directories import resolveFilename, SCOPE_PLUGINS

config.plugins.Sfootball = ConfigSubsection()
config.plugins.Sfootball.countries = ConfigSubList()
config.plugins.Sfootball.countries_count = ConfigNumber(default=0)
urlpath = 'http://www3.varzesh3.com/livescores.do'
sliderfile = resolveFilename(SCOPE_PLUGINS,
                             'Extensions/PersianLiveSoccer/images/slider.png')
c7color = 11403055
c2color = 16753920
c1color = 16776960
c3color = 15657130
c5color = 16711680
c4color = 16729344
c6color = 65407
c8color = 13047173
c9color = 13789470