Ejemplo n.º 1
0
class LastFMScreenMain(Screen, HelpableScreen, LastFM):
    skin = """
        <screen name="LastFM" position="center,center" size="600,440" title="%s" >
            
            <widget name="artist" position="0,5" size="100,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />          
            <widget name="album" position="0,45" size="100,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />          
            <widget name="track" position="0,85" size="100,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />          
            
            <widget name="info_artist" position="105,5" size="300,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />          
            <widget name="duration" position="420,5" size="60,30" valign=\"center\" halign=\"right\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />          
            <widget name="info_album" position="105,45" size="370,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />          
            <widget name="info_track" position="105,85" size="370,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />          
            <widget name="info_cover" position="484,5" size="116,116" />          
            
            <widget name="tablist" position="0,140" size="210,205" scrollbarMode="showOnDemand" />            
            <widget name="streamlist" position="220,140" size="380,205" scrollbarMode="showOnDemand" />            
            
            <widget name="button_red" position="0,360" size="140,40" valign=\"center\" halign=\"center\" zPosition=\"3\" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" font=\"Regular;18\" />          
            <widget name="button_green" position="140,360" size="140,40" valign=\"center\" halign=\"center\" zPosition=\"3\" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" font=\"Regular;18\"/>            
            <widget name="button_yellow" position="280,360" size="140,40" valign=\"center\" halign=\"center\" zPosition=\"3\" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" font=\"Regular;18\" />            
            <widget name="button_blue" position="420,360" size="140,40" valign=\"center\" halign=\"center\" zPosition=\"3\" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" font=\"Regular;18\" />             
            <ePixmap pixmap="buttons/red.png" position="0,360" zPosition="2" size="140,40" transparent="1" alphatest="on" />
            <ePixmap pixmap="buttons/green.png" position="140,360" zPosition="2" size="140,40" transparent="1" alphatest="on" />
            <ePixmap pixmap="buttons/yellow.png" position="280,360" zPosition="2" size="140,40" transparent="1" alphatest="on" />
            <ePixmap pixmap="buttons/blue.png" position="420,360" zPosition="2" size="140,40" transparent="1" alphatest="on" />
            <ePixmap position="570,370" size="35,25" pixmap="buttons/key_menu.png" alphatest="on" />
            <widget name="infolabel" position="10,410" size="500,20" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;16\" />           
        </screen>""" % (config.plugins.LastFM.name.value + " " + _("Ver.") +
                        " " + lastfm_pluginversion)  # title

    noCoverArtPNG = "no_coverArt.png"

    def __init__(self, session, streamplayer, args=0):
        self.skin = LastFMScreenMain.skin
        Screen.__init__(self, session)
        HelpableScreen.__init__(self)
        LastFM.__init__(self)
        self.session = session
        self.streamplayer = streamplayer  #StreamPlayer(session)
        self.streamplayer.onStateChanged.append(
            self.onStreamplayerStateChanged)
        self.imageconverter = ImageConverter(116, 116, self.setCoverArt)
        Screen.__init__(self, session)

        self.tabs = [(_("Personal Stations"), self.loadPersonalStations),
                     (_("Global Tags"), self.loadGlobalTags),
                     (_("Top Tracks"), self.loadTopTracks),
                     (_("Recent Tracks"), self.loadRecentTracks),
                     (_("Loved Tracks"), self.loadLovedTracks),
                     (_("Banned Tracks"), self.loadBannedTracks),
                     (_("Friends"), self.loadFriends),
                     (_("Neighbours"), self.loadNeighbours)]
        tablist = []
        for tab in self.tabs:
            tablist.append((tab[0], tab))
        self.tablist = MenuList(tablist)
        self.tablist.onSelectionChanged.append(self.action_TabChanged)

        self["artist"] = Label(_("Artist") + ":")
        self["duration"] = Label("-00:00")
        self["album"] = Label(_("Album") + ":")
        self["track"] = Label(_("Track") + ":")

        self["info_artist"] = Label("N/A")
        self["info_album"] = Label("N/A")
        self["info_track"] = Label("N/A")
        self["info_cover"] = Pixmap()

        self["tablist"] = self.tablist
        self["streamlist"] = MenuList([])

        self["button_red"] = Label(_("Play"))
        self["button_green"] = Label(_("Skip"))
        self["button_yellow"] = Label(_("Love"))
        self["button_blue"] = Label(_("Ban"))
        self["infolabel"] = Label("")

        self["actions"] = ActionMap(
            [
                "InfobarChannelSelection", "WizardActions", "DirectionActions",
                "MenuActions", "ShortcutActions", "GlobalActions",
                "HelpActions", "NumberActions"
            ], {
                "ok": self.action_ok,
                "back": self.action_exit,
                "red": self.action_startstop,
                "green": self.skipTrack,
                "yellow": self.love,
                "blue": self.banTrack,
                "historyNext": self.action_nextTab,
                "historyBack": self.action_prevTab,
                "menu": self.action_menu,
            }, -1)

        self.helpList.append((self["actions"], "WizardActions",
                              [("ok", _("Switch to selected Station"))]))
        self.helpList.append((self["actions"], "InfobarChannelSelection",
                              [("historyNext", _("Select next Tab"))]))
        self.helpList.append((self["actions"], "InfobarChannelSelection",
                              [("historyBack", _("Select prev Tab"))]))
        self.helpList.append((self["actions"], "InfobarChannelSelection",
                              [("switchChannelDown", _("Next Selection"))]))
        self.helpList.append((self["actions"], "InfobarChannelSelection",
                              [("switchChannelUp", _("Previous Selection"))]))
        self.helpList.append((self["actions"], "InfobarChannelSelection",
                              [("zapDown", _("Page forward Selections"))]))
        self.helpList.append((self["actions"], "InfobarChannelSelection",
                              [("zapUp", _("Page backward Selections"))]))
        self.helpList.append((self["actions"], "ShortcutActions",
                              [("red", _("Start/stop streaming"))]))
        self.helpList.append(
            (self["actions"], "ShortcutActions", [("green",
                                                   _("Skip current Track"))]))
        self.helpList.append(
            (self["actions"], "ShortcutActions", [("yellow",
                                                   _("Mark Track as loved"))]))
        self.helpList.append((self["actions"], "ShortcutActions",
                              [("blue", _("Ban Track, never play"))]))
        self.helpList.append((self["actions"], "MenuActions",
                              [("menu", _("Open") + " " + _("Setup"))]))
        self.helpList.append((self["actions"], "WizardActions", [
            ("back", _("Quit") + " " + config.plugins.LastFM.name.value)
        ]))

        self.onLayoutFinish.append(self.initLastFM)
        self.onLayoutFinish.append(self.tabchangedtimerFired)
        self.onLayoutFinish.append(self.setCoverArt)

        self.guiupdatetimer = eTimer()
        self.guiupdatetimer.timeout.get().append(self.guiupdatetimerFired)
        self.guiupdatetimer.start(
            config.plugins.LastFM.metadatarefreshinterval.value * 1000)

        self.tabchangetimer = eTimer()
        self.tabchangetimer.timeout.get().append(self.tabchangedtimerFired)

        self.infolabelcleartimer = eTimer()
        self.infolabelcleartimer.timeout.get().append(self.clearInfoLabel)

        self.screensavertimer = eTimer()
        self.screensavertimer.timeout.get().append(self.startScreensaver)
        self.onShown.append(self.startScreensaverTimer)

    def initLastFM(self):
        self.setInfoLabel(_("logging into last.FM"))
        self.connect(config.plugins.LastFM.username.value,
                     config.plugins.LastFM.password.value)

    def onStreamplayerStateChanged(self, reason):
        if reason is self.streamplayer.STATE_PLAYLISTENDS:
            self.loadPlaylist()
        else:
            pass

    def onConnectSuccessful(self, text):
        self.setInfoLabel(_("login successful"))

    def onConnectFailed(self, text):
        self.setInfoLabel(_("login failed! ") + text, timeout=False)

    def onTrackSkiped(self, reason):
        self.setInfoLabel(_("Track skipped"))

    def onTrackLoved(self, reason):
        self.setInfoLabel(_("Track loved"))

    def onTrackBanned(self, reason):
        self.setInfoLabel(_("Track banned"))

    def onCommandFailed(self, reason):
        self.setInfoLabel(reason)

    def onGlobalTagsLoaded(self, tags):
        self.setInfoLabel(_("Global Tags loaded"))
        self.buildMenuList(tags)

    def onTopTracksLoaded(self, tracks):
        self.setInfoLabel(_("Top Tracks loaded"))
        self.buildMenuList(tracks)

    def onRecentTracksLoaded(self, tracks):
        self.setInfoLabel(_("Recent Tracks loaded"))
        self.buildMenuList(tracks)

    def onRecentBannedTracksLoaded(self, tracks):
        self.setInfoLabel(_("Banned Tracks loaded"))
        self.buildMenuList(tracks)

    def onRecentLovedTracksLoaded(self, tracks):
        self.setInfoLabel(_("Loved Tracks loaded"))
        self.buildMenuList(tracks)

    def onNeighboursLoaded(self, user):
        self.setInfoLabel(_("Neighbours loaded"))
        self.buildMenuList(user)

    def onFriendsLoaded(self, user):
        self.setInfoLabel(_("Friends loaded"))
        self.buildMenuList(user)

    def onStationChanged(self, reason):
        self.setInfoLabel(reason)
        self.loadPlaylist()

    def onMetadataLoaded(self, metadata):
        self.updateGUI()
        self.guiupdatetimer.start(
            config.plugins.LastFM.metadatarefreshinterval.value * 1000)

    def onPlaylistLoaded(self, reason):
        self.streamplayer.setPlaylist(self.playlist)
        self.streamplayer.play()

    def skipTrack(self):
        self.streamplayer.skip()
        self.updateGUI()

    def banTrack(self):
        self.ban()
        self.streamplayer.skip()
        self.updateGUI()

    def action_TabChanged(self):
        self.tabchangetimer.stop()
        self.tabchangetimer.start(
            config.plugins.LastFM.timeouttabselect.value * 1000)

    def guiupdatetimerFired(self):
        self.updateGUI()
        self.guiupdatetimer.start(
            config.plugins.LastFM.metadatarefreshinterval.value * 1000)

    def tabchangedtimerFired(self):
        self.tablist.getCurrent()[1][1]()
        self.tabchangetimer.stop()

    def startScreensaverTimer(self):
        self.screensavertimer.start(
            config.plugins.LastFM.sreensaver.wait.value * 1000)

    def resetScreensaverTimer(self):
        self.screensavertimer.stop()
        self.screensavertimer.start(
            config.plugins.LastFM.sreensaver.wait.value * 1000)

    def startScreensaver(self):
        if config.plugins.LastFM.sreensaver.use.value:
            self.screensavertimer.stop()
            self.session.openWithCallback(self.updateGUI, LastFMSaveScreen,
                                          self)

    def action_nextTab(self):
        self.tablist.down()
        self.resetScreensaverTimer()

    def action_prevTab(self):
        self.tablist.up()
        self.resetScreensaverTimer()

    def action_menu(self):
        self.session.open(LastFMConfigScreen)
        self.resetScreensaverTimer()

    def action_exit(self):
        self.screensavertimer.stop()
        self.guiupdatetimer.stop()
        self.streamplayer.stop(force=True)
        self.streamplayer.onStateChanged = []

        self.close()

    def action_ok(self):
        x = self["streamlist"].l.getCurrentSelection()
        if x is None:
            pass
        elif len(x) > 1:
            if not x[1].startswith('lastfm://'):
                self.customstationtype = x[1]
                text = _("please enter an %s name to listen to" % x[1])
                texts = _("%s name" % x[1])
                self.session.openWithCallback(
                    self.onTextForCustomStationEntered,
                    InputBox,
                    windowTitle=text,
                    title=texts)
            else:
                self.changeStation(x[1])
                self.resetScreensaverTimer()

    def onTextForCustomStationEntered(self, text):
        print("onTextForCustomStationEntered", text, self.customstationtype)
        if text is not None:
            if self.customstationtype == "artist":
                self.changeStation(
                    urllib2_qoute("lastfm://artist/%s/similarartists" % text))
            elif self.customstationtype == "groupe":
                self.changeStation(urllib2_qoute("lastfm://group/%s" % text))
            elif self.customstationtype == "tag":
                self.changeStation(
                    urllib2_qoute("lastfm://globaltags/%s" % text))

    def action_startstop(self):
        self.resetScreensaverTimer()
        if self.streamplayer.is_playing:
            self.streamplayer.stop(force=True)
            self.setInfoLabel(_("Stream stopped"))
        else:
            self.setInfoLabel(_("Starting stream"), timeout=True)
            self.loadPlaylist()
            self.updateGUI(
            )  #forcing guiupdate, so we dont wait till guiupdatetimer fired
            self.guiupdatetimer.start(
                config.plugins.LastFM.metadatarefreshinterval.value * 1000)

    def setInfoLabel(self, text, timeout=True):
        self.infolabelcleartimer.stop()
        self["infolabel"].setText(text)
        if timeout is True:
            self.infolabelcleartimer.start(
                config.plugins.LastFM.timeoutstatustext.value * 1000)

    def clearInfoLabel(self):
        self["infolabel"].setText("")

    def updateGUI(self):

        if self.streamplayer.is_playing is True:
            self["duration"].setText(self.streamplayer.getRemaining())
            self["button_red"].setText(_("Stop"))
        else:
            self["duration"].setText("00:00")
            self["button_red"].setText(_("Play"))

        if self.streamplayer.is_playing is not True or self.shown is not True:
            return None

        if self.streamplayer.is_playing is True:
            self.setTitle(config.plugins.LastFM.name.value + " " + _("Ver.") +
                          lastfm_pluginversion + " " +
                          self.streamplayer.getMetadata("station"))
            self["info_artist"].setText(
                self.streamplayer.getMetadata("creator"))
            self["info_album"].setText(self.streamplayer.getMetadata("album"))
            self["info_track"].setText(self.streamplayer.getMetadata("title"))
            self.summaries.setText(
                self.streamplayer.getMetadata("creator") + " - " +
                self.streamplayer.getMetadata("title"))
        else:
            self.setTitle("Last.FM")
            self["info_artist"].setText("N/A")
            self["info_album"].setText("N/A")
            self["info_track"].setText("N/A")
            self.summaries.setText("N/A")

        if self.streamplayer.getMetadata("image").startswith(
                "http") and config.plugins.LastFM.showcoverart.value:
            self.imageconverter.convert(self.streamplayer.getMetadata("image"))
        else:
            self.setCoverArt()

        if self.streamplayer.is_playing is not True:
            self.setTitle(myname)
            self.setCoverArt()
            self["info_artist"].setText("N/A")
            self["info_album"].setText("N/A")
            self["info_track"].setText("N/A")

    def setCoverArt(self, pixmap=None):
        if pixmap is None:
            self["info_cover"].instance.setPixmapFromFile(self.noCoverArtPNG)
        else:
            self["info_cover"].instance.setPixmap(pixmap)

    def loadPersonalStations(self):
        tags = []
        x = {}
        x["_display"] = _("Personal Recommendations")
        x["stationurl"] = self.getPersonalURL(
            config.plugins.LastFM.username.value,
            level=config.plugins.LastFM.recommendedlevel.value)
        tags.append(x)

        x = {}
        x["_display"] = _("Neighbours Tracks")
        x["stationurl"] = self.getNeighboursURL(
            config.plugins.LastFM.username.value)
        tags.append(x)

        x = {}
        x["_display"] = _("Loved Tracks")
        x["stationurl"] = self.getLovedURL(
            config.plugins.LastFM.username.value)
        tags.append(x)

        x = {}
        x["_display"] = _("Play Artist Radio...")
        x["stationurl"] = 'artist'
        tags.append(x)

        x = {}
        x["_display"] = _("Play Group Radio...")
        x["stationurl"] = 'groupe'
        tags.append(x)

        x = {}
        x["_display"] = _("Play Tag Radio...")
        x["stationurl"] = 'tag'
        tags.append(x)

        creator = self.streamplayer.getMetadata("creator")
        if creator != "no creator" and creator != "N/A":
            x = {}
            x["_display"] = _(
                "Tracks similar to") + " " + self.streamplayer.getMetadata(
                    "creator")
            x["stationurl"] = self.getSimilarArtistsURL(artist=creator)
            tags.append(x)

            x = {}
            x["_display"] = _("Tracks liked by Fans of"
                              ) + " " + self.streamplayer.getMetadata(
                                  "creator")
            x["stationurl"] = self.getArtistsLikedByFans(artist=creator)
            tags.append(x)

            x = {}
            x["_display"] = _(
                "Group of") + " " + self.streamplayer.getMetadata("creator")
            x["stationurl"] = self.getArtistGroup(artist=creator)
            tags.append(x)

        self.buildMenuList(tags)

    def loadGlobalTags(self):
        self.setInfoLabel(_("Loading Global Tags"))
        tags = self.getGlobalTags()

    def loadTopTracks(self):
        self.setInfoLabel(_("Loading Top Tacks"))
        tracks = self.getTopTracks(config.plugins.LastFM.username.value)

    def loadRecentTracks(self):
        self.setInfoLabel(_("Loading Recent Tracks"))
        tracks = self.getRecentTracks(config.plugins.LastFM.username.value)

    def loadLovedTracks(self):
        self.setInfoLabel(_("Loading Loved Tracks"))
        tracks = self.getRecentLovedTracks(
            config.plugins.LastFM.username.value)

    def loadBannedTracks(self):
        self.setInfoLabel(_("Loading Loved Tracks"))
        tracks = self.getRecentBannedTracks(
            config.plugins.LastFM.username.value)

    def loadNeighbours(self):
        self.setInfoLabel(_("Loading Neighbours"))
        tracks = self.getNeighbours(config.plugins.LastFM.username.value)

    def loadFriends(self):
        self.setInfoLabel(_("Loading Friends"))
        tracks = self.getFriends(config.plugins.LastFM.username.value)

    def buildMenuList(self, items):
        menuliste = []
        for i in items:
            menuliste.append((i['_display'], i['stationurl']))
        self["streamlist"].l.setList(menuliste)

    def createSummary(self):
        return lastfmLCDScreen
Ejemplo n.º 2
0
class Browser(Screen, HelpableScreen):

	def __init__(self, session, fullscreen = False, url = None, isHbbtv = False, isTransparent = False, hbbtvMenu = None):
		size = getDesktop(0).size()
		width = int(size.width() * 0.9)
		fwidth = int(size.width())
		height = int(size.height() * 0.85)
		fheight = int(size.height())

		Browser.skin = """
			<screen name="Browser" position="center,center" size="%(w)d,%(h)d" title="Web Browser" backgroundColor="#FF000000">
				<widget name="cursor" position="0,0" size="19,30" zPosition="1" alphatest="on"/>
				<widget name="url" position="0,0" zPosition="2" size="%(w)d,25" font="Regular;20" halign="left" valign="bottom" backgroundColor="background"/>
				<widget name="loading" position="%(loadingX)d,0" zPosition="3" size="150,25" font="Regular;20" halign="right" valign="bottom" backgroundColor="background"/>
				<widget name="urlList" position="0,30" zPosition="2" size="%(w)d,150" backgroundColor="background"/>
				<widget name="text" position="%(textX)d,100" size="350,40" font="Regular;20"  zPosition="2" halign="center" valign="center" backgroundColor="background"/>
				<widget source="webnavigation" render="WebView" position="0,25" zPosition="0" size="%(w)d,%(mainH)d" transparent="1"/>
				<widget source="canvas" render="Canvas" position="0,25" zPosition="1" size="%(w)d,%(mainH)d" backgroundColor="#FF000000" transparent="1" alphatest="on"/>

				<group name="_buttonBar">
					<widget name="buttonBar" position="0,%(btnBarY)d" size="%(w)d,30" zPosition="0" backgroundColor="background" transparent="0" />
					<ePixmap pixmap="skin_default/buttons/button_red_off.png" position="5,%(btnY)d" size="15,16" alphatest="on" />
					<widget source="button_red" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_red.png" position="5,%(btnY)d" size="15,16" alphatest="on">
						<convert type="ConditionalShowHide" />
					</widget>
					<widget name="red" position="25,%(btnTxtY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1" />

					<ePixmap pixmap="skin_default/buttons/button_green_off.png" position="195,%(btnY)d" size="15,16" alphatest="on" />
					<widget source="button_green" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_green.png" position="195,%(btnY)d" size="15,16" alphatest="on">
						<convert type="ConditionalShowHide" />
					</widget>
					<widget name="green" position="215,%(btnTxtY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1"/>

					<ePixmap pixmap="skin_default/buttons/button_yellow_off.png" position="385,%(btnY)d" size="15,16" alphatest="on" />
					<widget source="button_yellow" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_yellow.png" position="385,%(btnY)d" size="15,16" alphatest="on">
						<convert type="ConditionalShowHide" />
					</widget>
					<widget name="yellow" position="405,%(btnTxtY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1"/>

					<ePixmap pixmap="skin_default/buttons/button_blue_off.png" position="585,%(btnY)d" size="15,16" alphatest="on" />
					<widget source="button_blue" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_blue.png" position="585,%(btnY)d" size="15,16" alphatest="on">
						<convert type="ConditionalShowHide" />
					</widget>
					<widget name="blue" position="605,%(btnTxtY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1"/>
				</group>
				<widget name="statuslabel" position="%(notifX)d,%(btnTxtY)d" size="350,20" font="Regular;18"  zPosition="3" halign="right" valign="center" backgroundColor="background" />
			</screen>
			""" %{	"w" : width,
					"h" : height,
					"loadingX" : width-150,
					"textX" : (width - 375) / 2,
					"mainH" : height-55,
					"btnY" : height-22,
					"btnTxtY" : height-24,
					"btnBarY" : height - 30,
					"notifX" : width-350
				}

		Browser.skinFullscreen = """
			<screen name="BrowserFullscreen" flags="wfNoBorder" position="center,center" size="%(w)d,%(h)d" title="Web Browser" backgroundColor="#FF000000">
				<widget name="cursor" position="0,0" size="19,30" zPosition="1" alphatest="on"/>
				<widget name="url" position="75,75" zPosition="2" size="%(urlW)d,25" font="Regular;20" halign="left" valign="bottom" backgroundColor="background"/>
				<widget name="loading" position="%(loadingX)d,%(loadingY)d" zPosition="2" size="200,50" font="Regular;20" halign="center" valign="center" backgroundColor="background"/>
				<widget name="urlList" position="75,100" zPosition="2" size="%(urlW)d,150" backgroundColor="background" transparent="0" />
				<widget name="text" position="%(textX)d,100" size="350,40" font="Regular;20"  zPosition="2" halign="center" valign="center" backgroundColor="background" transparent="0" />
				<widget source="webnavigation" render="WebView" position="0,0" zPosition="0" size="%(w)d,%(h)d" transparent="1"/>
				<widget source="canvas" render="Canvas" position="0,0" zPosition="1" size="%(w)d,%(h)d" backgroundColor="#FF000000" transparent="1" alphatest="on"/>

				<group name="_buttonBar">
					<widget name="buttonBar" position="%(btnBarX)d,%(btnBarY)d" size="200,110" zPosition="0" backgroundColor="background" transparent="0" />
					<widget source="button_red_off" render="Pixmap" pixmap="skin_default/buttons/button_red_off.png" position="%(btnX)d,%(btnRedY)d" size="15,16" zPosition="1" alphatest="on">
						<convert type="ConditionalShowHide" />
					</widget>
					<widget source="button_red" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_red.png" position="%(btnX)d,%(btnRedY)d" size="15,16" alphatest="on">
						<convert type="ConditionalShowHide" />
					</widget>
					<widget name="red" position="%(btnTxtX)d,%(btnRedY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1"/>

					<widget source="button_green_off" render="Pixmap" pixmap="skin_default/buttons/button_green_off.png" position="%(btnX)d,%(btnGreenY)d" size="15,16" zPosition="1" alphatest="on">
						<convert type="ConditionalShowHide" />
					</widget>
					<widget source="button_green" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_green.png" position="%(btnX)d,%(btnGreenY)d" size="15,16" alphatest="on">
						<convert type="ConditionalShowHide" />
					</widget>
					<widget name="green" position="%(btnTxtX)d,%(btnGreenY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1"/>

					<widget source="button_yellow_off" render="Pixmap" pixmap="skin_default/buttons/button_yellow_off.png" position="%(btnX)d,%(btnYellowY)d" size="15,16" zPosition="1" alphatest="on">
						<convert type="ConditionalShowHide" />
					</widget>
					<widget source="button_yellow" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_yellow.png" position="%(btnX)d,%(btnYellowY)d" size="15,16" alphatest="on">
						<convert type="ConditionalShowHide" />
					</widget>
					<widget name="yellow" position="%(btnTxtX)d,%(btnYellowY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1"/>

					<widget source="button_blue_off" render="Pixmap" pixmap="skin_default/buttons/button_blue_off.png" position="%(btnX)d,%(btnBlueY)d" size="15,16" zPosition="1" alphatest="on">
						<convert type="ConditionalShowHide" />
					</widget>
					<widget source="button_blue" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_blue.png" position="%(btnX)d,%(btnBlueY)d" size="15,16" alphatest="on">
						<convert type="ConditionalShowHide" />
					</widget>
					<widget name="blue" position="%(btnTxtX)d,%(btnBlueY)d" size="160,25" zPosition="1" font="Regular;18" halign="left" valign="top" backgroundColor="background" transparent="1"/>
				</group>

				<widget name="statuslabel" position="%(notifX)d,%(loadingY)d" size="350,50" zPosition="1" font="Regular;18" halign="center" valign="center" backgroundColor="background" transparent="0" />
			</screen>
			""" %{	"w" : fwidth,
					"h" : fheight,
					"urlW": fwidth - 150,
					"loadingY" : fheight - 125,
					"loadingX" : ( fwidth / 2 ) - 75,
					"textX" : (fwidth - 375) / 2,
					"mainH" : fheight-55,
					"btnBarX": fwidth - 75 - 200,
					"btnBarY": fheight - 75 - 108,
					"btnX" : fwidth - 75 - 190,
					"btnTxtX" : fwidth - 75 - 165,
					"btnRedY" : fheight - 75 - 100,
					"btnGreenY" : fheight - 75 - 75,
					"btnYellowY" : fheight - 75 - 50,
					"btnBlueY" : fheight - 75 - 25,
					"notifX" : ( fwidth / 2 ) - 175,
				}

		self.__isHbbtv = isHbbtv
		if self.__isHbbtv:
			isTransparent = fullscreen = True

		self.__hbbtvMenu = hbbtvMenu

		self.__isTransparent = isTransparent
		self.__fullscreen = fullscreen
		if self.__fullscreen:
			Browser.skin = Browser.skinFullscreen

		Screen.__init__(self, session)
		HelpableScreen.__init__(self)

		if self.__fullscreen:
			self.skinName = "BrowserFullscreen"

		self.__startUrl = url

		self["loading"] = Label("")

		self.urlInput = EnhancedInput()
		self["url"] = self.urlInput

		self.textInput = Input()
		self["text"] = self.textInput
		self.textInput.hide()

		self.statuslabel = Label("")
		self["statuslabel"] = self.statuslabel
		self.statuslabel.hide();

		self.urlInputEnabled = False

		self.webnavigation = WebNavigation()
		self.webnavigation.zoomFactor = 1.0
		self.__onStoragePathChanged()
		self["webnavigation"] = self.webnavigation

		self.__urlList = MenuList([], enableWrapAround = True, content = eListboxPythonStringContent)
		self["urlList"] = self.__urlList

		self.canvas =  CanvasSource()
		self["canvas"] = self.canvas

		self["buttonBar"] = Label("")
		self["button_red_off"] = Boolean(True)
		self["button_green_off"] = Boolean(True)
		self["button_yellow_off"] = Boolean(True)
		self["button_blue_off"] = Boolean(True)
		self["button_red"] = Boolean(True)
		self["button_green"] = Boolean(False)
		self["button_yellow"] = Boolean(True)
		self["button_blue"] = Boolean(True)
		self["red"] = Label(_("Mouse Off"))
		self["green"] = Label("")
		self["yellow"] = Label(_("Navigation"))
		self["blue"] = Label(_("Pagescroll"))

		self["cursor"] = Pixmap()
		self.__cursorPos = ePoint(50,50)
		self.__mouseMode = False

		self.__db = BrowserDB.getInstance()
		self.pageTitle = ""

		self.__urlSuggestionTimer = eTimer()
		self.__urlSuggestionTimer_conn = self.__urlSuggestionTimer.timeout.connect(self.__onSuggestionTimeout)
		self.__inputTimer = eTimer()
		self.__inputTimer_conn = self.__inputTimer.timeout.connect(self.onInputTimer)
		self.__statusTimer = eTimer()
		self.__statusTimer_conn = self.__statusTimer.timeout.connect(self.__hideStatus)

		self.__scrollMode = False
		self.__zoomMode = False
		self.__isInput = False
		self.__hasSslErrors = False
		self.__handledUnsupportedContent = False
		self.__currentPEM = None
		self.__currentUser = None
		self.__currentPass = None
		self.__currentRealm = None
		self.__keyboardMode = eRCInput.getInstance().getKeyboardMode()

		self.onFirstExecBegin.append(self.__onFirstExecBegin)
		self.onExecEnd = []
		self.onPageLoadFinished = []
		self.onActionTv = []
		self.onActionRecord = []
		self.onUrlChanged = []

		self["helpableactions"] = HelpableActionMap(self, "BrowserActions",
		{
			"exit": (self.__actionExit, _("Close the browser")),
			"url": (self.__actionEnterUrl, _("Enter web address or search term")),
			"back": self.__actionBack,
			"forward": self.__actionForward,
			"left": self.__actionLeft,
			"right": self.__actionRight,
			"up": self.__actionUp,
			"down": self.__actionDown,
			"pageUp": (self.__actionPageUp, _("Page Up / Zoom in")),
			"pageDown": (self.__actionPageDown, _("Page Down / Zoom out")),
			"seekBack": boundFunction(self.__actionNavigate, eWebView.navMediaRewind),
			"seekFwd": boundFunction(self.__actionNavigate, eWebView.navMediaFastForward),
			"tab": (boundFunction(self.__actionNavigate, eWebView.navTab), _("Tab")),
			"backspace": (self.__actionBackspace, _("Backspace / Navigate back")),
			"backtab": boundFunction(self.__actionNavigate, eWebView.navBacktab),
			"delete": (self.__actionDelete, _("Delete / Navigate forward")),
			"ascii": self.__actionAscii,
			"text" : (self.__actionVirtualAscii, _("Open Virtual Keyboard")),
			"ok" : self.__actionOk,
			"enter" : self.__actionEnter,
			"menu" : (self.__actionMenu, _("Menu")),
			"fullscreen" : self.__actionFullscreen,
			"play" : self.__actionPlay,
			"pause" : self.__actionPause,
			"playpause" : self.__actionPlayPause,
			"stop" : self.actionStop,
			"tv" : self.__actionTv,
			"record" : self.__actionRecord,
		}, -2)

		self["coloractions"] = ActionMap(["ColorActions"],
		{
			"red" : self.__actionRed,
			"green" : self.__actionGreen,
			"yellow" : self.__actionYellow,
			"blue" : self.__actionBlue,
		})

		self["numberactions"] = NumberActionMap(["NumberActions"],
		{
			"1": self.keyNumberGlobal,
			"2": self.keyNumberGlobal,
			"3": self.keyNumberGlobal,
			"4": self.keyNumberGlobal,
			"5": self.keyNumberGlobal,
			"6": self.keyNumberGlobal,
			"7": self.keyNumberGlobal,
			"8": self.keyNumberGlobal,
			"9": self.keyNumberGlobal,
			"0": self.keyNumberGlobal
		})

	def execEnd(self):
		Screen.execEnd(self)
		for fnc in self.onExecEnd:
			fnc()

	def setBackgroundTransparent(self, enabled):
		self.webnavigation.setBackgroundTransparent(enabled)

	def __setKeyBoardModeAscii(self):
		eRCInput.getInstance().setKeyboardMode(eRCInput.kmAscii)

	def __unsetKeyBoardModeAscii(self):
		eRCInput.getInstance().setKeyboardMode(self.__keyboardMode)

	def __setStatus(self, text):
		print "[Browser].__setStatus"
		self.statuslabel.setText(text)
		self.statuslabel.show()
		self.__statusTimer.startLongTimer(3)

	def __hideStatus(self):
		self["statuslabel"].hide()
		self.__statusTimer.stop()

	def __setMouseMode(self, enabled):
		self.__mouseMode = enabled
		if enabled:
			self.__setCursor()
			self["cursor"].show()
			self["red"].setText("Mouse On")
			self.__clearCanvas()
		else:
			self["cursor"].hide()
			self["red"].setText("Mouse Off")

	def __actionExit(self):
		if self.__isHbbtv:
			self.__actionExitCB(True)
			return
		self.session.openWithCallback(self.__actionExitCB, MessageBox, _("Do you really want to exit the browser?"), type = MessageBox.TYPE_YESNO)

	def __actionExitCB(self, confirmed):
		if confirmed:
			self.__urlSuggestionTimer.stop()
			self.__inputTimer.stop()
			if not self.__isHbbtv:
				config.plugins.WebBrowser.lastvisited.value = self.webnavigation.url
				config.plugins.WebBrowser.lastvisited.save()
			self.__persistCookies()
			self.close()

	def __onFirstExecBegin(self):
		self["cursor"].instance.setPixmapFromFile(resolveFilename(SCOPE_PLUGINS, "Extensions/Browser/cursor.png"))
		self.__setCursor()
		self.__setMouseMode(self.__mouseMode)

		#enable/disable transparent background
		self.setBackgroundTransparent(self.__isTransparent)
		#set Accept-Language header to current language
		lang = '-'.join(language.getLanguage().split('_'))
		self.webnavigation.setAcceptLanguage(lang)
		self.__registerCallbacks()
		self.__urlList.hide()
		self.__restoreCookies()
		if self.__fullscreen:
			self.__showHideBars(False)
			self.__showHideButtonBar(False)
		if self.__startUrl is None:
			if config.plugins.WebBrowser.startPage.value == "home":
				self.__actionHome()
			else:
				self.setUrl(config.plugins.WebBrowser.lastvisited.value)
		else:
			self.setUrl(self.__startUrl)

	def __clearCanvas(self):
		size = getDesktop(0).size()
		self.canvas.fill(0, 0, size.width(), size.height(), 0xFF000000)
		self.canvas.flush()

	def __onStoragePathChanged(self):
		if config.plugins.WebBrowser.storage.enabled.value:
			self.webnavigation.enablePersistentStorage(config.plugins.WebBrowser.storage.path.value)

	def __onMicroFocusChanged(self, x, y, w, h, isInput):
		if not self.__isHbbtv and not self.__mouseMode:
			self.__cursorPos.setX(x)
			self.__cursorPos.setY(y)

			if self.__isInput and not isInput:
				self.__unsetKeyBoardModeAscii()

			self.__isInput = isInput
			if self.__isInput:
				self.setKeyboardModeAscii()

			self.__clearCanvas()
			lw = 4 #line width
			y = y
			x = x - lw
			w = w + lw
			blo = y + h #bottom line offset
			color =0xFF9900 #line color

			self.canvas.fill(x, y, lw, h, color)#left line
			self.canvas.fill(x, blo, w, lw, color)#bottom line
			self.canvas.flush()#Done -> Flush

	def __onSuggestionTimeout(self):
		needle = self.urlInput.getText()
		if needle != "":
			list = self.__db.suggsetUrls(self.urlInput.getText())
			list.insert(0, needle)
			list.insert(1, _("Search for '%s'") %needle)
			self.__urlList.setList(list)
			self.__urlList.moveToIndex(0)
			self.__urlList.show()
		else:
			self.__urlList.hide()

	def __onAuthRequired(self, token, user, password, realm):
		if self.__currentUser != None and self.__currentPassword != None and realm == self.__currentRealm:
			d = eDict()
			d.setString("user", self.__currentUser)
			d.setString("password", self.__currentPassword)
			self.webnavigation.setDict(token, d)
			self.__currentUser = None
			self.__currentPassword = None
			self.__currentRealm = None
		else:
			msgbox = self.session.openWithCallback(self.__onAuthRequiredCB, HttpAuthenticationDialog, user, password, realm)
			msgbox.setTitle(_("Authentication required"))

	def __onAuthRequiredCB(self, dict):
		if dict != None:
			self.__currentUser = dict["user"]
			self.__currentPassword = dict["password"]
			self.__currentRealm = dict["realm"]
			self.setUrl(self.webnavigation.url)

	def __onProxyAuthRequired(self, token, user, password, realm):
		self.onAuthRequired(token, user, password, realm)

	def __onDownloadRequested(self, url):
		print "[Browser].__onDownloadRequested '%s'" %(url)
		filename = url_unquote(url).split("/")[-1]
		localfile = "%s/%s" %(config.plugins.WebBrowser.downloadpath.value, filename)
		downloadManager.AddJob(DownloadJob(url, localfile, filename))
		self.session.open(MessageBox, _("Download started..."), type = MessageBox.TYPE_INFO, timeout = 3)

	def __onUnsupportedContent(self, url, contentType):
		print "[Browser].__onUnsupportedContent 'url=%s; contentType='%s'" %(url, contentType)
		self.__handledUnsupportedContent = True
		if contentType.startswith("video") or contentType.startswith("audio"):
			list = [( _("Download"), ("download", url) ),
					( _("Play"), ("play", url) )]
			self.session.openWithCallback(self.__onUnsupportedContentCB, ChoiceBox, title=_("You've selected a media file what do you want to do?"), list = list)
		else:
			self.__onDownloadRequested(url)

	def __onUnsupportedContentCB(self, answer):
		if answer != None:
			answer = answer and answer[1]
			if answer[0] == "download":
				self.__onDownloadRequested(answer[1])
			else:
				service = eServiceReference(4097,0,answer[1])
				self.session.open(MoviePlayer, service)

	def __actionMenu(self):
		if self.__isHbbtv:
			if self.__hbbtvMenu is not None:
				self.__hbbtvMenu()
			return

		self.__urlSuggestionTimer.stop()
		self.__inputTimer.stop()
		self.__urlList.hide()
		self.__persistCookies()
		self.session.openWithCallback(self.__menuCB, BrowserMenu, self.pageTitle, self.webnavigation.url)

	def __menuCB(self, actions = None):
		if actions != None:
			for action in actions:
				if action[0] == BrowserMenu.ACTION_BOOKMARK:
					self.setUrl(action[1])
				elif action[0] == BrowserMenu.ACTION_COOKIES:
					self.__restoreCookies()
				elif action[0] == BrowserMenu.ACTION_STORAGE_PATH:
					self.__onStoragePathChanged()

		if self.skinName == "BrowserFullscreen" and not config.plugins.WebBrowser.fullscreen.value:
			self.__requireRestart()
		if self.skinName != "BrowserFullscreen" and config.plugins.WebBrowser.fullscreen.value:
			self.__requireRestart()

	def __requireRestart(self):
		text = _("Some of the configuration changes require a restart of the Browser.\nDo you want to restart the Browser now?")
		msgbox = self.session.openWithCallback(self.__requireRestartCB, MessageBox, text, type = MessageBox.TYPE_YESNO)
		msgbox.setTitle(_("Restart required"))

	def __requireRestartCB(self, confirmed):
		if confirmed:
			self.close(self.session, True, self.webnavigation.url)

	def __enableUrlInput(self):
		self.urlInputEnabled = True
		self.urlInput.markAll()
		self.__setKeyBoardModeAscii()
		if self.__fullscreen:
			self.__showHideBars()

	def __disableUrlInput(self, hide = True):
		self.urlInputEnabled = False
		self.__urlSuggestionTimer.stop()
		self.__urlList.hide()
		self.urlInput.markNone()
		if not self.__isInput:
			self.__unsetKeyBoardModeAscii()
		if self.__fullscreen and hide:
			self.__showHideBars(False)

	def __showHideButtonBar(self, visible = True):
		if visible:
			self["_buttonBar"].show()
		else:
			self["_buttonBar"].hide()
			
		used_buttons = ("button_red_off", "button_green_off", "button_yellow_off",
			"button_blue_off", "button_red", "button_yellow", "button_blue")
		for button in used_buttons:
			self[button].setBoolean(visible)
		#disable green
		self["button_green"].setBoolean(False)

	def __showHideBars(self, visible = True):
		if self.__fullscreen:
			if visible:
				self.urlInput.show()
			else:
				self.urlInput.hide()

			if not self.__isHbbtv:
				self.__showHideButtonBar(visible)

	def __registerCallbacks(self):
		print "[Browser].__registerCallbacks"
		self.webnavigation.onUrlChanged.append(self.__onUrlChanged)
		self.webnavigation.onTitleChanged.append(self.__onTitleChanged)
		self.webnavigation.onLoadProgress.append(self.__onLoadProgress)
		self.webnavigation.onLoadFinished.append(self.__onLoadFinished)
		self.webnavigation.onDownloadRequested.append(self.__onDownloadRequested)
		self.webnavigation.onUnsupportedContent.append(self.__onUnsupportedContent)
		self.webnavigation.onMicroFocusChanged.append(self.__onMicroFocusChanged)
		self.webnavigation.onWindowRequested.append(self.__onWindowRequested)
		self.webnavigation.onSslErrors.append(self.__onSslErrors)
		self.webnavigation.onAuthRequired.append(self.__onAuthRequired)
		self.webnavigation.onProxyAuthRequired.append(self.__onProxyAuthRequired)

	def __actionOk(self):
		if self.textInput.visible:
			self.onInputTimer()
		elif self.urlInputEnabled:
			if self.__urlList.visible and self.__urlList.getSelectedIndex() > 0:
				if self.__urlList.getSelectedIndex() == 1:
					self.__searchUsingCurrentUrlValue()
					self.__disableUrlInput(False)
				else:
					self.urlInput.setText(self.__urlList.getCurrent())
					self.urlInput.end()
					self.__urlList.hide()
			else:
				self.setUrl(self.urlInput.getText())
				self.__isInput = False
				self.__disableUrlInput(False)

		else:
			if self.__mouseMode:
				self.webnavigation.leftClick(self.__cursorPos)
			else:
				self.__actionNavigate(eWebView.navOpenLink)

	def __actionEnter(self):
		if self.textInput.visible or self.urlInputEnabled:
			self.__actionOk()
		else:
			if self.__mouseMode:
				self.webnavigation.leftClick(self.__cursorPos)
			else:
				self.__actionNavigate(eWebView.navOpenLink)

	def __actionPlay(self):
		self.__actionNavigate(eWebView.navMediaPlay)

	def __actionPause(self):
		self.__actionNavigate(eWebView.navMediaPause)

	def __actionPlayPause(self):
		self.__actionNavigate(eWebView.navMediaPlay) #playpause doesn't work anywhere, but play does (HBBTV)

	def actionStop(self):
		self.__actionNavigate(eWebView.navMediaStop)

	def __actionBack(self):
		if self.__isHbbtv:
			self.__actionNavigate(eWebView.navBack)
		else:
			self.__actionNavigate(eWebView.navBackExplicit)

	def __actionForward(self):
		if self.__isHbbtv:
			self.__actionNavigate(eWebView.navForward)
		else:
			self.__actionNavigate(eWebView.navForwardExplicit)

	def __actionBackspace(self):
		if self.textInput.visible:
			self.restartTimer()
			self.textInput.deleteBackward()
		elif self.urlInputEnabled:
			self.urlInput.deleteBackward()
			self.__onUrlInputChanged()
		else:
			if self.__isInput:
				self.__actionNavigate(eWebView.navBackspace)
			else:
				self.__actionBack()

	def __actionDelete(self):
		if self.textInput.visible:
			self.restartTimer()
			self.textInput.delete()
		elif self.urlInputEnabled:
			self.urlInput.delete()
			self.__onUrlInputChanged()
		else:
			if self.__isInput:
				self.__actionNavigate(eWebView.navDelete)
			else:
				self.__actionForward()

	def __moveCursor(self, x=0, y=0):
		if x != 0 or y != 0:
			wSize = self.webnavigation.size
			#horizontal
			if x != 0:
				x = self.__cursorPos.x() + x
				w = wSize.width()
				if x <= 2:
					x = 2
					self.__scroll(0-int(config.plugins.WebBrowser.scrollOffset.value), 0)
				elif x >= w-2:
					x = w-2
					self.__scroll(int(config.plugins.WebBrowser.scrollOffset.value), 0)
				self.__cursorPos.setX(x)
			#vertical
			if y != 0:
				y = self.__cursorPos.y() + y
				h = wSize.height()
				if y < 2:
					y = 2
					self.__scroll(0, 0-int(config.plugins.WebBrowser.scrollOffset.value))
				elif y > h-2:
					y = h-2
					self.__scroll(0, int(config.plugins.WebBrowser.scrollOffset.value))
				self.__cursorPos.setY(y)
		self.__setCursor()

	def __setCursor(self):
		wPos = self.webnavigation.position
		relPos = None
		if wPos.x() > 0 or wPos.y() > 0:
			relPos = ePoint(self.__cursorPos.x() + wPos.x(), self.__cursorPos.y() + wPos.y())
		else:
			relPos = self.__cursorPos
		self["cursor"].move(relPos)

	def __actionLeft(self):
		if self.urlInputEnabled:
			self.urlInput.left()
		elif self.__scrollMode:
			self.__scroll(0-int(config.plugins.WebBrowser.scrollOffset.value), 0)
		elif self.textInput.visible:
			self.restartTimer()
			self.textInput.left()
		else:
			if self.__mouseMode:
				self.__moveCursor(x=-10)
			else:
				self.__actionNavigate(eWebView.navLeft)

	def __actionRight(self):
		if self.urlInputEnabled:
			self.urlInput.right()
		elif self.__scrollMode:
			self.__scroll(int(config.plugins.WebBrowser.scrollOffset.value), 0)
		elif self.textInput.visible:
			self.restartTimer()
			self.textInput.right()
		else:
			if self.__mouseMode:
				self.__moveCursor(x=10)
			else:
				self.__actionNavigate(eWebView.navRight)

	def __actionUp(self):
		if self.urlInputEnabled:
			if self.__urlList.visible:
				self.__urlList.up()
		elif self.__scrollMode:
			self.__scroll(0, 0-int(config.plugins.WebBrowser.scrollOffset.value))
		elif self.textInput.visible:
			self.restartTimer()
			self.textInput.up()
		else:
			if self.__mouseMode:
				self.__moveCursor(y=-10)
			else:
				self.__actionNavigate(eWebView.navUp)

	def __actionDown(self):
		if self.urlInputEnabled:
			if self.__urlList.visible:
				self.__urlList.down()
			#else:
			#	self.urlInput.down()
		elif self.__scrollMode:
			self.__scroll(0, int(config.plugins.WebBrowser.scrollOffset.value))
		elif self.textInput.visible:
			self.restartTimer()
			self.textInput.down()
		else:
			if self.__mouseMode:
				self.__moveCursor(y=10)
			else:
				self.__actionNavigate(eWebView.navDown)

	def __actionTv(self):
		for fnc in self.onActionTv:
			if fnc() is True: #Function told us to stop handling
				return

	def __actionRecord(self):
		for fnc in self.onActionRecord:
			if fnc() is True: #Function told us to stop handling
				return

	def __scroll(self, dx, dy):
		self.webnavigation.scroll(dx, dy)

	def __actionRed(self):
		if self.__isHbbtv:
			self.__actionNavigate(eWebView.navRed)
		else:
			self.__setMouseMode(not self.__mouseMode)

	def __actionGreen(self):
		self.__actionNavigate(eWebView.navGreen)

	def __actionYellow(self):
		if self.__isHbbtv:
			self.__actionNavigate(eWebView.navYellow)
		else:
			self.__scrollMode = not self.__scrollMode
			enDis = _("disabled")
			mode = _("Navigation")
			if self.__scrollMode:
				enDis = _("enabled")
				mode = _("Scrolling")
			text = _("Scroll mode is now %s") %enDis
			self["yellow"].setText(mode)
			self.__setStatus(text)

	def __actionBlue(self):
		if self.__isHbbtv:
			self.__actionNavigate(eWebView.navBlue)
		else:
			self.__zoomMode = not self.__zoomMode
			enDis = _("disabled")
			mode = _("Pagescroll")
			if self.__zoomMode:
				enDis = _("enabled")
				mode = _("Zoom")
			text = _("Zoom mode is now %s") %enDis
			self["blue"].setText(mode)
			self.__setStatus(text)

	def restartTimer(self):
		self.__inputTimer.stop()
		self.__inputTimer.startLongTimer(5)

	def __onUrlChanged(self, url):
		if url != None:
			self.__clearCanvas()
			self.urlInput.setText(url)
			self.urlInput.markNone()
			if self.__fullscreen and not self.__isHbbtv:
				self.__showHideBars()

			for fnc in self.onUrlChanged:
				fnc(url)

	def __onTitleChanged(self, title):
		if title != None:
			self.pageTitle = title
			self.setTitle("Web Browser - %s" %self.pageTitle)

	def __onLoadProgress(self, progress):
		print "[Browser].__onLoadProgress %s" %progress
		if(progress < 100):
			self["loading"].show()
			self["loading"].setText(_("Loading... %s%%" %progress))
		else:
			self["loading"].hide()
			self["loading"].setText("")

	def __onLoadFinished(self, val):
		print "[Browser].__onLoadFinished %s" %val
		if val == 1:
			if not self.__isHbbtv:
				self.__db.addToHistory(HistoryItem(title = self.pageTitle, url = self.webnavigation.url));
			if self.__fullscreen:
				self.__showHideBars(False)
		else:
			if not self.__hasSslErrors and not self.__handledUnsupportedContent:
				self.__handledUnsupportedContent = False
		for fnc in self.onPageLoadFinished:
			fnc()

	def __searchUsingCurrentUrlValue(self):
		needle = self.urlInput.getText()
		if needle != "":
			needle = needle.replace("http://", "").replace("https://", "").replace("ftp://", "")
			self.__onSearchRequested(needle)

	def __onSearchRequested(self, needle):
		if needle != "" and needle != None:
			needle = url_quote_plus(needle)
			url = "%s%s" %(config.plugins.WebBrowser.searchProvider.value, needle)
			self.setUrl(url)

	def __onWindowRequested(self, url):
		print "[Browser].__onWindowRequested :: '%s'" %url
		self.setUrl(url)

	def __onSslErrors(self, token, errors, pems):
		print "[Browser].__onSslErrors :: 'token='%s', errors='%s'" %(token, errors)
		self.__hasSslErrors = True
		cnt = 0
		perrors = {}
		pems = list(pems)
		pems.sort()
		for bytes in pems:
			pem = "".join(map(chr, bytes))
			if pem.strip() != "":
				messages = perrors.get(pem, [])
				messages.append(errors[cnt])
				perrors[pem] = messages
				cnt += 1

		for pem, messages in perrors.iteritems():
			cert = Certificate(-1, self.__getCurrentNetloc(), pem)
			checkVal = self.__db.checkCert( cert ) == BrowserDB.CERT_UNKOWN
			if checkVal == BrowserDB.CERT_OK:
				print "[Browser].__onSslErrors :: netloc/pem combination known and trusted!"
				dict = eDict()
				dict.setFlag("ignore")
				self.webnavigation.setDict(token, dict)
			else:
				print "[Browser].__onSslErrors :: netloc/pem combination NOT known and/or trusted!"
				self.__currentPEM = pem

				errorstr = ""
				for m in messages:
					errorstr = "%s\n%s" %(m, errorstr)

				text = ""
				if checkVal == BrowserDB.CERT_UNKOWN:
					text = _("A certificate for the desired secure connection has the following errors:\n%s\nDo you want to add an exception for this certificate and accept connections to this host anyways?") %errorstr
				elif checkVal == BrowserDB.CERT_CHANGED:
					text = _("ATTENTION!\nPotential security breach detected!\nA certificate for the desired secure connection has CHANGED!\nIn addition it has the following errors:\n%s\nDo you want to add an exception for this certificate and accept connections to this host anyways?") %errorstr
				msgbox = self.session.openWithCallback( self.__onSslErrorCB, MessageBox, text, type = MessageBox.TYPE_YESNO)
				msgbox.setTitle(_("Certificate errors!"))

	def __onSslErrorCB(self, confirmed):
		self.__hasSslErrors = False
		if confirmed:
			print "[Browser].__onSslErrorCB :: loc='%s', PEM='%s'" %(self.__getCurrentNetloc(), self.__currentPEM)
			self.__db.addCert( Certificate(-1, self.__getCurrentNetloc(), self.__currentPEM) )
			self.setUrl(self.webnavigation.url)

	def __getCurrentNetloc(self):
		return self.__getNetloc(self.webnavigation.url)

	def __getNetloc(self, url):
		return urlparse(url).netloc

	def __actionHome(self):
		self.setUrl(config.plugins.WebBrowser.home.value)

	def __actionEnterUrl(self):
		if self.urlInputEnabled:
			self.__disableUrlInput()
		else:
			self.__enableUrlInput()

	def setUrl(self, url):
		if url != None:
			if url.find("://") == -1:
				url = "http://%s" %url
			if url:
				self.webnavigation.url = url

	def getUserAgent(self):
		return self.webnavigation.useragent

	def setUserAgent(self, useragent):
		self.webnavigation.useragent = useragent

	def __actionAscii(self):
		if self.urlInputEnabled:
			self.urlInput.handleAscii(getPrevAsciiCode())
			self.__onUrlInputChanged()
		elif self.__isInput:
			self.webnavigation.changed(WebNavigation.COMMAND_ASCII_INPUT, getPrevAsciiCode())
		else:
			self.__actionNavigateNumber(chr(getPrevAsciiCode()))

	def __actionNavigateNumber(self, char):
		print "[Browser].__actionNavigateNumber %s" %char
		nav = { '0' : eWebView.nav0,
				'1' : eWebView.nav1,
				'2' : eWebView.nav2,
				'3' : eWebView.nav3,
				'4' : eWebView.nav4,
				'5' : eWebView.nav5,
				'6' : eWebView.nav6,
				'7' : eWebView.nav7,
				'8' : eWebView.nav8,
				'9' : eWebView.nav9,
				}

		action = nav.get(str(char), None)
		if action != None:
			if self.__mouseMode:
				self.__actionMouseJump(char)
			else:
				self.__actionNavigate(action)

	def __actionMouseJump(self, char):
		size = self.webnavigation.size
		off = 100 #offset

		hcenter = size.width() / 2
		vcenter = size.height() / 2

		roff = size.width() - off #right offset
		boff = size.height() - off # bottom offset

		offsets = {
			'1' : [off,off],
			'2' : [hcenter, off],
			'3' : [roff, off],
			'4' : [off, vcenter],
			'5' : [hcenter, vcenter],
			'6' : [roff, vcenter],
			'7' : [off, boff],
			'8' : [hcenter, boff],
			'9' : [roff, boff],
			}
		offset = offsets.get(str(char), None)
		if offset:
			self.__cursorPos.setX(offset[0])
			self.__cursorPos.setY(offset[1])
			self.__setCursor()

	def __actionVirtualAscii(self):
		self.session.openWithCallback(self.sendTextAsAscii, VirtualKeyBoard, title="Browser Input")

	def __actionPageUp(self):
		if self.__zoomMode:
			self.webnavigation.zoomFactor += 0.1
		else:
			self.__actionNavigate(eWebView.navPageUp)

	def __actionPageDown(self):
		if self.__zoomMode:
			self.webnavigation.zoomFactor -= 0.1
		else:
			self.__actionNavigate(eWebView.navPageDown)

	def sendTextAsAscii(self, text):
		if text != None:
			for c in text:
				self.webnavigation.changed(WebNavigation.COMMAND_ASCII_INPUT, ord(c))

	def __actionNavigate(self, param):
		if not self.urlInputEnabled and not self.textInput.visible:
			self.webnavigation.changed(WebNavigation.COMMAND_NAVIGATE, param)

	def keyNumberGlobal(self, number):
		if self.urlInputEnabled:
			self.urlInput.number(number)
			self.__onUrlInputChanged()
		elif self.__isInput:
			self.textInput.show()
			self.restartTimer()
			self.textInput.number(number)
		else:
			self.__actionNavigateNumber(number)

	def __onUrlInputChanged(self):
		if not self.__urlSuggestionTimer.isActive():
			self.__urlSuggestionTimer.startLongTimer(1)

	def onInputTimer(self):
		self.__inputTimer.stop()
		self.textInput.hide()
		text = self.textInput.getText()
		self.textInput.setText("")
		if text != "" and text != None:
			self.sendTextAsAscii(text)

	def __actionFullscreen(self):
		self.webnavigation.size = (self.width, self.height)
		self.webnavigation.position = (0, 0)

	def __restoreCookies(self):
		cookies = self.__db.getCookies()
		print "[Browser].__restoreCookies ::: restoring %s cookies" %len(cookies)
		rawCookies = []
		for cookie in cookies:
			rawCookies.append( b64encode(cookie.raw) )
		self.webnavigation.cookies = ','.join(rawCookies)

	def __persistCookies(self):
		rawCookies = self.webnavigation.cookies
		if rawCookies.strip() != "":
			rawCookies = rawCookies.split(",")
			cookies = []
			cookie = None
			for rawCookie in rawCookies:
				cookie = Cookie.fromRawString(b64decode(rawCookie))
				if cookie != None:
					cookies.append( cookie )
			print "[Browser].__persistCookies ::: persisting %s cookies" %len(cookies)
			self.__db.persistCookies(cookies)
		else:
			print "[Browser].__persistCookies ::: NO cookies to be persisted"
Ejemplo n.º 3
0
class LastFMScreenMain(Screen, HelpableScreen, LastFM):
    skin = """
        <screen name="LastFM" position="center,center" size="600,440" title="%s" >

            <widget name="artist" position="0,5" size="100,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />
            <widget name="album" position="0,45" size="100,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />
            <widget name="track" position="0,85" size="100,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />

            <widget name="info_artist" position="105,5" size="300,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />
            <widget name="duration" position="420,5" size="60,30" valign=\"center\" halign=\"right\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />
            <widget name="info_album" position="105,45" size="370,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />
            <widget name="info_track" position="105,85" size="370,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />
            <widget name="info_cover" position="484,5" size="116,116" />

            <widget name="tablist" position="0,140" size="210,205" scrollbarMode="showOnDemand" />
            <widget name="streamlist" position="220,140" size="380,205" scrollbarMode="showOnDemand" />

            <widget name="key_red" position="0,360" size="140,40" valign=\"center\" halign=\"center\" zPosition=\"3\" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" font=\"Regular;18\" />
            <widget name="key_green" position="140,360" size="140,40" valign=\"center\" halign=\"center\" zPosition=\"3\" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" font=\"Regular;18\"/>
            <widget name="key_yellow" position="280,360" size="140,40" valign=\"center\" halign=\"center\" zPosition=\"3\" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" font=\"Regular;18\" />
            <widget name="key_blue" position="420,360" size="140,40" valign=\"center\" halign=\"center\" zPosition=\"3\" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" font=\"Regular;18\" />
            <ePixmap pixmap="skin_default/buttons/red.png" position="0,360" zPosition="2" size="140,40" transparent="1" alphatest="on" />
            <ePixmap pixmap="skin_default/buttons/green.png" position="140,360" zPosition="2" size="140,40" transparent="1" alphatest="on" />
            <ePixmap pixmap="skin_default/buttons/yellow.png" position="280,360" zPosition="2" size="140,40" transparent="1" alphatest="on" />
            <ePixmap pixmap="skin_default/buttons/blue.png" position="420,360" zPosition="2" size="140,40" transparent="1" alphatest="on" />
            <ePixmap position="570,370" size="35,25" pixmap="skin_default/buttons/key_menu.png" alphatest="on" />
            <widget name="infolabel" position="10,410" size="500,20" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;16\" />
        </screen>""" % (config.plugins.LastFM.name.value + " " + _("Ver.") + " " + lastfm_pluginversion)  # title

    noCoverArtPNG = "/usr/share/enigma2/skin_default/no_coverArt.png"

    def __init__(self, session, streamplayer, args=0):
        self.skin = LastFMScreenMain.skin
        Screen.__init__(self, session)
        HelpableScreen.__init__(self)
        LastFM.__init__(self)
        self.session = session
        self.streamplayer = streamplayer  # StreamPlayer(session)
        self.streamplayer.onStateChanged.append(self.onStreamplayerStateChanged)
        self.imageconverter = ImageConverter(116, 116, self.setCoverArt)
        Screen.__init__(self, session)

        self.tabs = [
            (_("Personal Stations"), self.loadPersonalStations),
            (_("Global Tags"), self.loadGlobalTags),
            (_("Top Tracks"), self.loadTopTracks),
            (_("Recent Tracks"), self.loadRecentTracks),
            (_("Loved Tracks"), self.loadLovedTracks),
            (_("Banned Tracks"), self.loadBannedTracks),
            (_("Friends"), self.loadFriends),
            (_("Neighbours"), self.loadNeighbours)
        ]
        tablist = []
        for tab in self.tabs:
            tablist.append((tab[0], tab))
        self.tablist = MenuList(tablist)
        self.tablist.onSelectionChanged.append(self.action_TabChanged)

        self["artist"] = Label(_("Artist") + ":")
        self["duration"] = Label("-00:00")
        self["album"] = Label(_("Album") + ":")
        self["track"] = Label(_("Track") + ":")

        self["info_artist"] = Label("N/A")
        self["info_album"] = Label("N/A")
        self["info_track"] = Label("N/A")
        self["info_cover"] = Pixmap()

        self["tablist"] = self.tablist
        self["streamlist"] = MenuList([])

        self["key_red"] = Label(_("Play"))
        self["key_green"] = Label(_("Skip"))
        self["key_yellow"] = Label(_("Love"))
        self["key_blue"] = Label(_("Ban"))
        self["infolabel"] = Label("")

        self["actions"] = HelpableActionMap(self, ["InfobarChannelSelection", "WizardActions", "ShortcutActions", "MenuActions"], {
            "ok": (self.action_ok, _("Switch to selected station")),
            "back": (self.action_exit, _("Quit") + " " + config.plugins.LastFM.name.value),
            "red": (self.action_startstop, _("Start/stop streaming")),
            "green": (self.skipTrack, _("Skip current track")),
            "yellow": (self.love, _("Mark track as loved")),
            "blue": (self.banTrack, _("Ban track, never play")),
            "historyNext": (self.action_nextTab, _("Select next tab")),
            "historyBack": (self.action_prevTab, _("Select prev tab")),

            "menu": (self.action_menu, _("Open setup menu")),
        }, prio=-1, description=config.plugins.LastFM.name.value)

        # Unimplemented actions that were given help entries.
        # Perhaps there was an intention to implement them at some stage.

        # self.helpList.append((self["actions"], "InfobarChannelSelection", [("switchChannelDown", _("Next selection"))]))
        # self.helpList.append((self["actions"], "InfobarChannelSelection", [("switchChannelUp", _("Previous selection"))]))
        # self.helpList.append((self["actions"], "InfobarChannelSelection", [("zapDown", _("Page forward selections"))]))
        # self.helpList.append((self["actions"], "InfobarChannelSelection", [("zapUp", _("Page backward selections"))]))

        self.onLayoutFinish.append(self.initLastFM)
        self.onLayoutFinish.append(self.tabchangedtimerFired)
        self.onLayoutFinish.append(self.setCoverArt)

        self.guiupdatetimer = eTimer()
        self.guiupdatetimer.timeout.get().append(self.guiupdatetimerFired)
        self.guiupdatetimer.start(config.plugins.LastFM.metadatarefreshinterval.value * 1000)

        self.tabchangetimer = eTimer()
        self.tabchangetimer.timeout.get().append(self.tabchangedtimerFired)

        self.infolabelcleartimer = eTimer()
        self.infolabelcleartimer.timeout.get().append(self.clearInfoLabel)

        self.screensavertimer = eTimer()
        self.screensavertimer.timeout.get().append(self.startScreensaver)
        self.onShown.append(self.startScreensaverTimer)

    def initLastFM(self):
        self.setInfoLabel(_("logging into last.FM"))
        self.connect(config.plugins.LastFM.username.value, config.plugins.LastFM.password.value)

    def onStreamplayerStateChanged(self, reason):
        if reason is self.streamplayer.STATE_PLAYLISTENDS:
            self.loadPlaylist()
        else:
            pass

    def onConnectSuccessful(self, text):
        self.setInfoLabel(_("login successful"))

    def onConnectFailed(self, text):
        self.setInfoLabel(_("login failed! ") + text, timeout=False)

    def onTrackSkiped(self, reason):
        self.setInfoLabel(_("Track skipped"))

    def onTrackLoved(self, reason):
        self.setInfoLabel(_("Track loved"))

    def onTrackBanned(self, reason):
        self.setInfoLabel(_("Track banned"))

    def onCommandFailed(self, reason):
        self.setInfoLabel(reason)

    def onGlobalTagsLoaded(self, tags):
        self.setInfoLabel(_("Global Tags loaded"))
        self.buildMenuList(tags)

    def onTopTracksLoaded(self, tracks):
        self.setInfoLabel(_("Top Tracks loaded"))
        self.buildMenuList(tracks)

    def onRecentTracksLoaded(self, tracks):
        self.setInfoLabel(_("Recent Tracks loaded"))
        self.buildMenuList(tracks)

    def onRecentBannedTracksLoaded(self, tracks):
        self.setInfoLabel(_("Banned Tracks loaded"))
        self.buildMenuList(tracks)

    def onRecentLovedTracksLoaded(self, tracks):
        self.setInfoLabel(_("Loved Tracks loaded"))
        self.buildMenuList(tracks)

    def onNeighboursLoaded(self, user):
        self.setInfoLabel(_("Neighbours loaded"))
        self.buildMenuList(user)

    def onFriendsLoaded(self, user):
        self.setInfoLabel(_("Friends loaded"))
        self.buildMenuList(user)

    def onStationChanged(self, reason):
        self.setInfoLabel(reason)
        self.loadPlaylist()

    def onMetadataLoaded(self, metadata):
        self.updateGUI()
        self.guiupdatetimer.start(config.plugins.LastFM.metadatarefreshinterval.value * 1000)

    def onPlaylistLoaded(self, reason):
        self.streamplayer.setPlaylist(self.playlist)
        self.streamplayer.play()

    def skipTrack(self):
        self.streamplayer.skip()
        self.updateGUI()

    def banTrack(self):
        self.ban()
        self.streamplayer.skip()
        self.updateGUI()

    def action_TabChanged(self):
        self.tabchangetimer.stop()
        self.tabchangetimer.start(config.plugins.LastFM.timeouttabselect.value * 1000)

    def guiupdatetimerFired(self):
        self.updateGUI()
        self.guiupdatetimer.start(config.plugins.LastFM.metadatarefreshinterval.value * 1000)

    def tabchangedtimerFired(self):
        self.tablist.getCurrent()[1][1]()
        self.tabchangetimer.stop()

    def startScreensaverTimer(self):
        self.screensavertimer.start(config.plugins.LastFM.sreensaver.wait.value * 1000)

    def resetScreensaverTimer(self):
        self.screensavertimer.stop()
        self.screensavertimer.start(config.plugins.LastFM.sreensaver.wait.value * 1000)

    def startScreensaver(self):
        if config.plugins.LastFM.sreensaver.use.value:
            self.screensavertimer.stop()
            self.session.openWithCallback(self.updateGUI, LastFMSaveScreen, self)

    def action_nextTab(self):
        self.tablist.down()
        self.resetScreensaverTimer()

    def action_prevTab(self):
        self.tablist.up()
        self.resetScreensaverTimer()

    def action_menu(self):
        self.session.open(LastFMConfigScreen)
        self.resetScreensaverTimer()

    def action_exit(self):
        self.screensavertimer.stop()
        self.guiupdatetimer.stop()
        self.streamplayer.stop(force=True)
        self.streamplayer.onStateChanged = []

        self.close()

    def action_ok(self):
        x = self["streamlist"].l.getCurrentSelection()
        if x is None:
            pass
        elif len(x) > 1:
            if not x[1].startswith('lastfm://'):
                self.customstationtype = x[1]
                text = _("please enter an %s name to listen to" % x[1])
                texts = _("%s name" % x[1])
                self.session.openWithCallback(
                    self.onTextForCustomStationEntered,
                    InputBox,
                    windowTitle=text,
                    title=texts
                )
            else:
                self.changeStation(x[1])
                self.resetScreensaverTimer()

    def onTextForCustomStationEntered(self, text):
        print "onTextForCustomStationEntered", text, self.customstationtype
        if text is not None:
            if self.customstationtype == "artist":
                self.changeStation(urllib2_qoute("lastfm://artist/%s/similarartists" % text))
            elif self.customstationtype == "groupe":
                self.changeStation(urllib2_qoute("lastfm://group/%s" % text))
            elif self.customstationtype == "tag":
                self.changeStation(urllib2_qoute("lastfm://globaltags/%s" % text))

    def action_startstop(self):
        self.resetScreensaverTimer()
        if self.streamplayer.is_playing:
            self.streamplayer.stop(force=True)
            self.setInfoLabel(_("Stream stopped"))
        else:
            self.setInfoLabel(_("Starting stream"), timeout=True)
            self.loadPlaylist()
            self.updateGUI()  # forcing guiupdate, so we dont wait till guiupdatetimer fired
            self.guiupdatetimer.start(config.plugins.LastFM.metadatarefreshinterval.value * 1000)

    def setInfoLabel(self, text, timeout=True):
        self.infolabelcleartimer.stop()
        self["infolabel"].setText(text)
        if timeout is True:
            self.infolabelcleartimer.start(config.plugins.LastFM.timeoutstatustext.value * 1000)

    def clearInfoLabel(self):
        self["infolabel"].setText("")

    def updateGUI(self):

        if self.streamplayer.is_playing is True:
            self["duration"].setText(self.streamplayer.getRemaining())
            self["key_red"].setText(_("Stop"))
        else:
            self["duration"].setText("00:00")
            self["key_red"].setText(_("Play"))

        if self.streamplayer.is_playing is not True or self.shown is not True:
            return None

        if self.streamplayer.is_playing is True:
            self.setTitle(config.plugins.LastFM.name.value + " " + _("Ver.") + lastfm_pluginversion + " " + self.streamplayer.getMetadata("station"))
            self["info_artist"].setText(self.streamplayer.getMetadata("creator"))
            self["info_album"].setText(self.streamplayer.getMetadata("album"))
            self["info_track"].setText(self.streamplayer.getMetadata("title"))
            self.summaries.setText(self.streamplayer.getMetadata("creator") + " - " + self.streamplayer.getMetadata("title"))
        else:
            self.setTitle("Last.FM")
            self["info_artist"].setText("N/A")
            self["info_album"].setText("N/A")
            self["info_track"].setText("N/A")
            self.summaries.setText("N/A")

        if self.streamplayer.getMetadata("image").startswith("http") and config.plugins.LastFM.showcoverart.value:
            self.imageconverter.convert(self.streamplayer.getMetadata("image"))
        else:
            self.setCoverArt()

        if self.streamplayer.is_playing is not True:
            self.setTitle(myname)
            self.setCoverArt()
            self["info_artist"].setText("N/A")
            self["info_album"].setText("N/A")
            self["info_track"].setText("N/A")

    def setCoverArt(self, pixmap=None):
        if pixmap is None:
            self["info_cover"].instance.setPixmapFromFile(self.noCoverArtPNG)
        else:
            self["info_cover"].instance.setPixmap(pixmap)

    def loadPersonalStations(self):
        tags = []
        x = {}
        x["_display"] = _("Personal Recommendations")
        x["stationurl"] = self.getPersonalURL(config.plugins.LastFM.username.value, level=config.plugins.LastFM.recommendedlevel.value)
        tags.append(x)

        x = {}
        x["_display"] = _("Neighbours Tracks")
        x["stationurl"] = self.getNeighboursURL(config.plugins.LastFM.username.value)
        tags.append(x)

        x = {}
        x["_display"] = _("Loved Tracks")
        x["stationurl"] = self.getLovedURL(config.plugins.LastFM.username.value)
        tags.append(x)

        x = {}
        x["_display"] = _("Play Artist Radio...")
        x["stationurl"] = 'artist'
        tags.append(x)

        x = {}
        x["_display"] = _("Play Group Radio...")
        x["stationurl"] = 'groupe'
        tags.append(x)

        x = {}
        x["_display"] = _("Play Tag Radio...")
        x["stationurl"] = 'tag'
        tags.append(x)

        creator = self.streamplayer.getMetadata("creator")
        if creator != "no creator" and creator != "N/A":
            x = {}
            x["_display"] = _("Tracks similar to") + " " + self.streamplayer.getMetadata("creator")
            x["stationurl"] = self.getSimilarArtistsURL(artist=creator)
            tags.append(x)

            x = {}
            x["_display"] = _("Tracks liked by Fans of") + " " + self.streamplayer.getMetadata("creator")
            x["stationurl"] = self.getArtistsLikedByFans(artist=creator)
            tags.append(x)

            x = {}
            x["_display"] = _("Group of") + " " + self.streamplayer.getMetadata("creator")
            x["stationurl"] = self.getArtistGroup(artist=creator)
            tags.append(x)

        self.buildMenuList(tags)

    def loadGlobalTags(self):
        self.setInfoLabel(_("Loading Global Tags"))
        tags = self.getGlobalTags()

    def loadTopTracks(self):
        self.setInfoLabel(_("Loading Top Tacks"))
        tracks = self.getTopTracks(config.plugins.LastFM.username.value)

    def loadRecentTracks(self):
        self.setInfoLabel(_("Loading Recent Tracks"))
        tracks = self.getRecentTracks(config.plugins.LastFM.username.value)

    def loadLovedTracks(self):
        self.setInfoLabel(_("Loading Loved Tracks"))
        tracks = self.getRecentLovedTracks(config.plugins.LastFM.username.value)

    def loadBannedTracks(self):
        self.setInfoLabel(_("Loading Loved Tracks"))
        tracks = self.getRecentBannedTracks(config.plugins.LastFM.username.value)

    def loadNeighbours(self):
        self.setInfoLabel(_("Loading Neighbours"))
        tracks = self.getNeighbours(config.plugins.LastFM.username.value)

    def loadFriends(self):
        self.setInfoLabel(_("Loading Friends"))
        tracks = self.getFriends(config.plugins.LastFM.username.value)

    def buildMenuList(self, items):
        menuliste = []
        for i in items:
            menuliste.append((i['_display'], i['stationurl']))
        self["streamlist"].l.setList(menuliste)

    def createSummary(self):
        return lastfmLCDScreen
Ejemplo n.º 4
0
class PictureViewer(Screen):
	skin = ""
	filelist = []
	currList = "slideshowlist"
	wbviewer = False
	loadedslideshowlistlistname = False

	def __init__(self, session, args = 0):
		skin =  """<screen position="93,70" size="550,450" title="%s">
		<widget name="menu" position="1,1" size="275,400"  scrollbarMode="showOnDemand" />
		<widget name="pixmap" position="275,1" size="275,200" backgroundColor="red" />
		<widget name="slist" position="275,200" size="275,200"  scrollbarMode="showOnDemand" />
		<widget name="key_red" position="6,405" size="130,40" backgroundColor="red" valign="center" halign="center" zPosition="2" foregroundColor="white" font="Regular;18" />
		<widget name="key_green" position="142,405" size="130,40" backgroundColor="green" valign="center" halign="center" zPosition="2" foregroundColor="white" font="Regular;18" />
		<widget name="key_yellow" position="278,405" size="130,40" backgroundColor="yellow" valign="center" halign="center" zPosition="2" foregroundColor="white" font="Regular;18" />
		<widget name="key_blue" position="414,405" size="130,40" backgroundColor="blue" valign="center" halign="center" zPosition="2" foregroundColor="white" font="Regular;18" />
		</screen>""" % config.plugins.pictureviewer.rootdir.value
		self.skin = skin
		Screen.__init__(self, session)

		self.filelist = PictureList(config.plugins.pictureviewer.rootdir.value, matchingPattern = config.plugins.pictureviewer.matchingPattern.value)
		self["menu"] = self.filelist

		self.preview = Pixmap()
		self["pixmap"] = self.preview

		self.slideshowfiles = []
		self.slideshowlist =MenuList(self.slideshowfiles)
		self["slist"] = self.slideshowlist

		self["key_red"] = Label("")
		self["key_green"] = Label("")
		self["key_yellow"] = Label("")
		self["key_blue"] = Label("")

		self["actions"] = ActionMap(["WizardActions", "MenuActions", "DirectionActions", "ShortcutActions"],
			{
			 "ok": self.go,
			 "back": self.close,
			 "menu": self.openMenu,
			 "up": self.up,
			 "down": self.down,
			 "left": self.leftUp,
			 "right": self.rightUp,
			 "red": self.KeyRed,
			 "green": self.KeyGreen,
			 "yellow": self.KeyYellow,
			 "blue": self.switchList,
			 }, -1)

		self.onLayoutFinish.append(self.switchList)
		self.onLayoutFinish.append(self.updateInfoPanel)

	def KeyGreen(self):
		if self.currList is "filelist":
			# adding all files in current dir to slideshowlist
			dirname = self["menu"].getCurrentDir()
			if os.path.isdir(dirname):
				s = os.listdir(dirname)
				s.sort()
				for file in s:
					if compile(config.plugins.pictureviewer.matchingPattern.value).search(dirname + file):
						self.slideshowfiles.append((_(file), dirname + file))
				self["slist"].l.setList(self.slideshowfiles)
		else:
			#loading list
			list = []
			try:
				for file in os.listdir(config.plugins.pictureviewer.slideshowdir.value):
					if file.endswith(config.plugins.pictureviewer.slideshowext.value):
						list.append((_(file.split("/")[-1]), file))
				self.session.openWithCallback(
						self.fileToLoadFilelistEntered,
						ChoiceBox,
						_("select List to load"),
						list
				)
			except IOError as e:
				print("["+myname+"] IOError:", e)
			except OSError as e:
				print("["+myname+"] OSError:", e)

	def KeyRed(self):
		if self.currList is "filelist" :
			#do slideshow
			self.hide()
			x = Slideshow(self.session, self.show)
			x.setfiles(self.slideshowfiles)
			x.start()
		else:
			# save filelist
			if not self.loadedslideshowlistlistname:
				newname = "slideshowlist"
			else:
				newname = self.loadedslideshowlistlistname
			self.session.openWithCallback(
					self.fileToSaveFilelistEntered,
					InputBox,
					title = _("Enter filename to save the List:"),
					text = newname,
					maxSize = False,
					type = Input.TEXT
			)

	def fileToLoadFilelistEntered(self, fileselection):
		if fileselection is not None:
			   try:
				   filename = fileselection[1]
				   fp = open(config.plugins.pictureviewer.slideshowdir.value + filename)
				   list = []
				   for x in fp.readlines():
					   file = x.replace("\n", "")
					   if x.startswith("#"):
						   pass
					   elif not os.path.exists(file):
						   print("["+myname+"] loaded file from filelist isnt avaible! ignoreing ->", file)
					   else:
						   list.append((_(file.split("/")[-1]), file))
				   self.slideshowfiles = list
				   self["slist"].l.setList(self.slideshowfiles)
				   self.loadedslideshowlistlistname = filename.replace(config.plugins.pictureviewer.slideshowext.value, "")
			   except IOError as e:
				   print("["+myname+"] error:", e)

	def fileToSaveFilelistEntered(self, filename):
		if filename is not None:
			print("["+myname+"] saving list to ", config.plugins.pictureviewer.slideshowdir.value+filename + config.plugins.pictureviewer.slideshowext.value)
			try:
				if not os.path.exists(config.plugins.pictureviewer.slideshowdir.value):
					print("+" * 10, os.path.basename(filename))
					os.mkdir(config.plugins.pictureviewer.slideshowdir.value)
				fp = open(config.plugins.pictureviewer.slideshowdir.value + filename+config.plugins.pictureviewer.slideshowext.value, "w")
				fp.write("# this is a slideshow file for "+myname+" made by V"+myversion+"\n")
				fp.write("# you can make your own... each line with full path of the imagefile\n")
				fp.write("# by importing this file,we will ignoring a file if is doesnt exist\n")
				for x in self.slideshowfiles:
					fp.write(x[1] + "\n")
				fp.close()
			except IOError as e:
				print("["+myname+"] error:", e)

	def KeyYellow(self):
		if self.currList is "filelist":
			# add picture to list
			fullfile = self["menu"].getSelection()[0]
			if os.path.isfile(fullfile):
				self.slideshowfiles.append((_(fullfile.split("/")[-1]), fullfile))
				self["slist"].l.setList(self.slideshowfiles)
		else:
			# deleting an Picture
			if len(self.slideshowfiles) >= 1:
				indexinlist = self["slist"].l.getCurrentSelectionIndex()
				self.slideshowfiles.pop(indexinlist)
				self["slist"].l.setList(self.slideshowfiles)

	def switchList(self):
		if self.currList is "filelist" :
			# Slideshow activieren
			self.filelist.selectionEnabled(0)
			self.slideshowlist.selectionEnabled(1)
			self["key_red"].setText("speichern")
			self["key_green"].setText("laden")
			self["key_yellow"].setText("loeschen")
			self["key_blue"].setText("Dateien")
			self.currList = "slideshowlist"
		else:
			# filelist activieren
			self.filelist.selectionEnabled(1)
			self.slideshowlist.selectionEnabled(0)
			self["key_red"].setText("starte Slideshow")
			self["key_green"].setText("alle hinzufuegen")
			self["key_yellow"].setText("hinzufuegen")
			self["key_blue"].setText("Slideshow bearbeiten")
			self.currList = "filelist"

	def go(self):
		if self.currList is "filelist" :
			selection = self["menu"].getSelection()
			if self.filelist.canDescent():
				self.setTitle(selection[0])
				self.filelist.descent()
			else:
				if selection[1] == True: # isDir
					pass
				else:
					print("["+myname+"] file selected ", selection[0])
					if os.path.isfile(selection[0]):
						self.session.open(PictureScreen, selection[0].split("/")[-1], selection[0])
					else:
						print("["+myname+"] file not found ", selection[0])
		else:
			self.updateInfoPanel()

	def up(self):
		 if self.currList is "filelist":
			 self.filelist.up()
			 self.updateInfoPanel()
		 else:
			 self.slideshowlist.up()

	def leftUp(self):
		 if self.currList is "filelist":
			 self.filelist.pageUp()
			 self.updateInfoPanel()
		 else:
			 self.slideshowlist.pageUp()

	def rightUp(self):
		if self.currList is "filelist":
			 self.filelist.pageDown()
			 self.updateInfoPanel()
		else:
			 self.slideshowlist.pageDown()

	def down(self):
		 if self.currList is "filelist":
			 self.filelist.down()
			 self.updateInfoPanel()
		 else:
			 self.slideshowlist.down()

	def updateInfoPanel(self):
		if self.currList is "filelist":
			selectedfile = self["menu"].getSelection()[0]
		else:
			selectedfile = self["slist"].l.getCurrentSelection()[1]
		sc=AVSwitch().getFramebufferScale()
		self.picload = ePicLoad()
		self.picload.PictureData.get().append(self.updateInfoPanelCB)
		self.picload.setPara((self["pixmap"].instance.size().width(), self["pixmap"].instance.size().height(), sc[0], sc[1], False, 1, "#FF000000"))
		self.picload.startDecode(selectedfile)


	def updateInfoPanelCB(self, picInfo = None):
		ptr = self.picload.getData()
		if ptr is not None:
			self["pixmap"].instance.setPixmap(ptr)
		else:
			pass

	def output(self, str):
		print("+" * 10, str)

	def openMenu(self):
		self.session.open(WebcamViewerMenu)
Ejemplo n.º 5
0
class BrowserMenu(Screen):
	ACTION_BOOKMARK = 0
	ACTION_COOKIES = 1
	ACTION_STORAGE_PATH = 2

	MENU_BOOKMARKS = 0
	MENU_SETTINGS = 1
	MENU_HISTORY = 2
	MENU_DOWNLOADS = 3
	MENU_CERTS = 4
	MENU_COOKIES = 5

	size = getDesktop(0).size()
	width = int(size.width() * 0.9)
	height = int(size.height() * 0.85)
	bof = height - 35 #Button-Offset

	skin = """
		<screen name="BrowserMenu" position="center,center" size="%(w)d,%(h)d" title="Web Browser - Menu" >
			<widget name="menu" position="0,0" zPosition="1" size="200,%(h)d" backgroundColor="#000000" transparent="1" />
			<widget source="line" render="Canvas" position="203,0" zPosition="2" size="4,%(h)d" backgroundColor="#000000" transparent="1" alphatest="on"/>
			<widget source="list" render="Listbox" position="210,0" zPosition="1" size="%(listW)d,%(listH)d" backgroundColor="#000000" transparent="1">
				<convert type="TemplatedMultiContent">
					{"templates":
						{"default": (55, [
							MultiContentEntryText(pos = (10, 1), size = (920, 25), font = 0, flags = RT_VALIGN_CENTER, text = 1),
							MultiContentEntryText(pos = (10, 30), size = (920, 25), font = 1, flags = RT_VALIGN_CENTER, text = 2),
						]),
						"history": (55, [
							MultiContentEntryText(pos = (10, 1), size = (150, 25), font = 1, flags = RT_VALIGN_CENTER, text = 1),
							MultiContentEntryText(pos = (10, 28), size = (150, 25), font = 1, flags = RT_VALIGN_CENTER, text = 2),
							MultiContentEntryText(pos = (190, 1), size = (690, 25), font = 0, flags = RT_VALIGN_CENTER, text = 3),
							MultiContentEntryText(pos = (190, 28), size = (690, 25), font = 1, flags = RT_VALIGN_CENTER, text = 4),
						]),
						"downloads": (25, [
							MultiContentEntryText(pos = (0, 1), size = (600, 24), font=1, flags = RT_HALIGN_LEFT, text = 1),
							MultiContentEntryText(pos = (610, 1), size = (150, 24), font=1, flags = RT_HALIGN_RIGHT, text = 2),
							MultiContentEntryProgress(pos = (760, 1), size = (100, 24), percent = 3),
							MultiContentEntryText(pos = (870, 1), size = (70, 24), font=1, flags = RT_HALIGN_RIGHT, text = 4),
						]),
						"certificates": (85, [
							MultiContentEntryText(pos = (10, 1), size = (150, 25), font = 1, flags = RT_VALIGN_CENTER, text = 1),
							MultiContentEntryText(pos = (10, 28), size = (150, 25), font = 1, flags = RT_VALIGN_CENTER, text = 2),
							MultiContentEntryText(pos = (190, 1), size = (690, 25), font = 0, flags = RT_VALIGN_CENTER, text = 3),
							MultiContentEntryText(pos = (190, 28), size = (690, 25), font = 1, flags = RT_VALIGN_CENTER, text = 4),
							MultiContentEntryText(pos = (10, 60), size = (900, 25), font = 0, flags = RT_VALIGN_CENTER, text = 5),
						]),
						"cookies": (75, [
							MultiContentEntryText(pos = (10, 1), size = (150, 25), font = 1, flags = RT_VALIGN_CENTER, text = 1),
							MultiContentEntryText(pos = (10, 28), size = (150, 25), font = 1, flags = RT_VALIGN_CENTER, text = 2),
							MultiContentEntryText(pos = (180, 1), size = (720, 25), font = 0, flags = RT_VALIGN_CENTER, text = 3),
							MultiContentEntryText(pos = (180, 28), size = (625, 25), font = 1, flags = RT_VALIGN_CENTER, text = 4),
							MultiContentEntryText(pos = (10, 60), size = (900, 15), font = 2, flags = RT_VALIGN_CENTER, text = 5),
						])
						},
					"fonts": [gFont("Regular", 22), gFont("Regular", 16), gFont("Regular", 13)]
					}
				</convert>
			</widget>
			<widget name="statuslabel" position="210,%(inputY)d" size="%(listW)d,25" font="Regular;20"  zPosition="2" halign="center" valign="center" backgroundColor="#000000" transparent="0" />
			<widget name="input" position="210,%(inputY)d" zPosition="1" size="%(listW)d,25" font="Regular;20" halign="left" valign="bottom" backgroundColor="#000000" transparent="1"/>
			<widget name="config" position="210,0" zPosition="2" size="%(listW)d,%(configH)d" backgroundColor="background" transparent="0" />

			<ePixmap pixmap="skin_default/buttons/button_red_off.png" position="210,%(btnY)d" size="15,16" alphatest="on" />
			<widget source="button_red" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_red.png" position="210,%(btnY)d" size="15,16" alphatest="on">
				<convert type="ConditionalShowHide" />
			</widget>
			<widget name="red" position="230,%(btnTxtY)d" size="100,20" foregroundColor="white" backgroundColor="background" font="Regular;18" transparent="1" halign="left" valign="top"/>

			<ePixmap pixmap="skin_default/buttons/button_green_off.png" position="340,%(btnY)d" size="15,16" zPosition="1" alphatest="on" />
			<widget source="button_green" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_green.png" position="340,%(btnY)d" size="15,16" alphatest="on">
				<convert type="ConditionalShowHide" />
			</widget>
			<widget name="green" position="360,%(btnTxtY)d" size="100,20" foregroundColor="white" backgroundColor="background" font="Regular;18" transparent="1" halign="left" valign="top"/>

			<ePixmap pixmap="skin_default/buttons/button_yellow_off.png" position="470,%(btnY)d" size="15,16" alphatest="on" />
			<widget source="button_yellow" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_yellow.png" position="470,%(btnY)d" size="15,16" alphatest="on">
				<convert type="ConditionalShowHide" />
			</widget>
			<widget name="yellow" position="490,%(btnTxtY)d" size="100,20" foregroundColor="white" backgroundColor="background" font="Regular;18" transparent="1" halign="left" valign="top"/>

			<ePixmap pixmap="skin_default/buttons/button_blue_off.png" position="600,%(btnY)d" size="15,16" alphatest="on" />
			<widget source="button_blue" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_blue.png" position="600,%(btnY)d" size="15,16" alphatest="on">
				<convert type="ConditionalShowHide" />
			</widget>
			<widget name="blue" position="620,%(btnTxtY)d" size="200,20" foregroundColor="white" backgroundColor="background" font="Regular;18" transparent="1" halign="left" valign="top"/>
		</screen>
		""" %{ 	"w" : width,
				"h" : height,
				"listW" : width - 210, "listH" : height - 90,
				"inputY" : height - 80,
				"configH" : height - 90,
				"btnY" : bof + 2,
				"btnTxtY" : bof
			}

	def __init__(self, session, currentTitle, currentUrl, menulist = None):
		Screen.__init__(self, session)

		self.currentUrl = currentUrl
		self.currentTitle = currentTitle

		#Menu
		if menulist is None:
			self.menu = MenuList([
						(_("Bookmarks"), self.MENU_BOOKMARKS),
						(_("History"), self.MENU_HISTORY),
						(_("Downloads"), self.MENU_DOWNLOADS),
						(_("Certificates"), self.MENU_CERTS),
						(_("Cookies"), self.MENU_COOKIES),
						(_("Settings"), self.MENU_SETTINGS),
				], enableWrapAround = True)
		else:
			self.menu = MenuList(menulist, enableWrapAround=True)
		self["menu"] = self.menu

		self["statuslabel"] = Label("")
		self["statuslabel"].hide()

		#Color Buttons
		self["button_red"] = Boolean(False)
		self["button_green"] = Boolean(False)
		self["button_yellow"] = Boolean(False)
		self["button_blue"] = Boolean(False)
		self.red = Label("")
		self.green = Label("")
		self.yellow = Label("")
		self.blue = Label("")
		self["red"] = self.red
		self["green"] = self.green
		self["yellow"] = self.yellow
		self["blue"] = self.blue

		#Lists
		self.detailList = List([], enableWrapAround = True)
		self.detailConfigList = ConfigList([])
		self.detailConfigList.l.setSeperation( (BrowserMenu.width - 210) / 2 )
		config.plugins.WebBrowser.storage.enabled.addNotifier(self.__cfgExpandableElementChanged, initial_call = False)
		config.plugins.WebBrowser.storage.enabled.addNotifier(self.__cfgStoragePathChanged, initial_call = False)
		config.plugins.WebBrowser.storage.path.addNotifier(self.__cfgStoragePathChanged, initial_call = False)

		self.detailInput = EnhancedInput()

		self["list"] = self.detailList
		self["config"] = self.detailConfigList
		self["input"] = self.detailInput
		self["line"] = CanvasSource()

		self.__cfgCreateSetup()

		self.__db = BrowserDB.getInstance()
		self.__curMenu = self.MENU_BOOKMARKS
		self.__bmList = None
		self.__hisList = None
		self.__crtList = None
		self.__ckList = None
		self.__bmNeedle = ""
		self.__bmFilterTimer = eTimer()
		self.__bmFilterTimer_conn = self.__bmFilterTimer.timeout.connect(self.__bmFilterCB)
		self.__hisNeedle = ""
		self.__hisFilterTimer = eTimer()
		self.__hisFilterTimer_conn = self.__hisFilterTimer.timeout.connect(self.__hisFilterCB)
		self.__dlRefreshTimer = eTimer()
		self.__dlRefreshTimer_conn = self.__dlRefreshTimer.timeout.connect(self.__dlBuildList)
		self.__statusTimer = eTimer()
		self.__statusTimer_conn = self.__statusTimer.timeout.connect(self.__hideStatus)
		self.__actions = []

		self.onFirstExecBegin.append(self.__drawSeparator)
		self.onFirstExecBegin.append(self.__onMenuChanged)
		self.onExecBegin.append(self.__reloadData)
		self.onShow.append(self.setKeyboardModeAscii)

		self["actions"] = ActionMap(["BrowserActions", "ColorActions"],
		{
			"ok" : self.__actionOk,
			"enter" : self.__actionOk,
			"exit" : self.__actionExit,
			"pageUp" : self.__actionMenuUp,
			"pageDown" : self.__actionMenuDown,
			"up" : boundFunction(self.__action, "up"),
			"down" : boundFunction(self.__action, "down"),
			"left" : boundFunction(self.__action, "left"),
			"right" : boundFunction(self.__action, "right"),
			"red" : boundFunction(self.__action, "red"),
			"green" : boundFunction(self.__action, "green"),
			"yellow" : boundFunction(self.__action, "yellow"),
			"blue" : boundFunction(self.__action, "blue"),
			"backspace" : boundFunction(self.__action, "backspace"),
			"delete" : boundFunction(self.__action, "delete"),
			"ascii": boundFunction(self.__action, "ascii"),
			# TODO "text" : self.__text
		}, -2)

		self["numberactions"] = NumberActionMap(["NumberActions"],
		{
			"1": self.__keyNumberGlobal,
			"2": self.__keyNumberGlobal,
			"3": self.__keyNumberGlobal,
			"4": self.__keyNumberGlobal,
			"5": self.__keyNumberGlobal,
			"6": self.__keyNumberGlobal,
			"7": self.__keyNumberGlobal,
			"8": self.__keyNumberGlobal,
			"9": self.__keyNumberGlobal,
			"0": self.__keyNumberGlobal
		}, -2)

		self.__actionFuncs = {
			self.MENU_BOOKMARKS : {
				"up" : self.detailList.selectPrevious,
				"down" : self.detailList.selectNext,
				"left" : self.detailList.selectPrevious,
				"right" : self.detailList.pageDown,
				"ok" : self.__bmOk,
				"enter" : self.__bmOk,
				"red" : self.__bmDelete,
				"green" : self.__bmAdd,
				"yellow" : self.__bmEdit,
				"blue" : self.__bmSetCurrentAsHome,
				"backspace" : self.__bmKeyBackspace,
				"delete" : self.__bmKeyDelete,
				"ascii": self.__bmKeyAscii,
				},
			self.MENU_HISTORY : {
				"up" : self.detailList.selectPrevious,
				"down" : self.detailList.selectNext,
				"left" : self.detailList.pageUp,
				"right" : self.detailList.pageDown,
				"ok" : self.__hisOk,
				"enter" : self.__hisOk,
				"red" : self.__hisClear,
				"blue" : self.__hisSetCurrentAsHome,
				"backspace" : self.__hisKeyBackspace,
				"delete" : self.__hisKeyDelete,
				"ascii": self.__hisKeyAscii,
				},
			self.MENU_SETTINGS : {
				"up" : self.__cfgKeyUp,
				"down" : self.__cfgKeyDown,
				"left" : self.__cfgKeyLeft,
				"right" : self.__cfgKeyRight,
				"ok" : self.__cfgKeyOK,
				"enter" : self.__cfgKeyOK,
				"red" : self.__cfgCancel,
				"green" : self.__cfgSave,
				"backspace" : self.__cfgKeyBackspace,
				"delete" : self.__cfgKeyDelete,
				"ascii": self.__cfgKeyAscii,
				},
			self.MENU_DOWNLOADS : {
				"up" : self.detailList.selectPrevious,
				"down" : self.detailList.selectNext,
				"left" : self.detailList.pageUp,
				"right" : self.detailList.pageDown,
				"red" : self.__dlAbort,
				},
			self.MENU_CERTS : {
				"up" : self.detailList.selectPrevious,
				"down" : self.detailList.selectNext,
				"left" : self.detailList.pageUp,
				"right" : self.detailList.pageDown,
				"red" : self.__crtDelete,
				"green" : self.__crtDetails,
				},
			self.MENU_COOKIES : {
				"up" : self.detailList.selectPrevious,
				"down" : self.detailList.selectNext,
				"left" : self.detailList.pageUp,
				"right" : self.detailList.pageDown,
				"red" : self.__ckDelete,
				"blue" : self.__ckDeleteAll,
				}
		}

	def _close(self):
		config.plugins.WebBrowser.storage.enabled.removeNotifier(self.__cfgExpandableElementChanged)
		config.plugins.WebBrowser.storage.enabled.removeNotifier(self.__cfgStoragePathChanged)
		config.plugins.WebBrowser.storage.path.removeNotifier(self.__cfgStoragePathChanged)
		self.close(self.__actions)

	def __actionOk(self):
		if self["statuslabel"].visible:
			self["statuslabel"].hide()
		else:
			self.__action("ok")

	def __actionExit(self):
		if self["statuslabel"].visible:
			self["statuslabel"].hide()
		else:
			if self.detailConfigList.isChanged():
				self.__cfgSave()
			self._close()

	def __actionMenuUp(self):
		self.menu.up()
		self.__onMenuChanged()

	def __actionMenuDown(self):
		self.menu.down()
		self.__onMenuChanged()

	def __reloadData(self):
		self.__bmList = self.__db.getBookmarks()
		self.__hisList = self.__db.getHistory()
		self.__crtList = self.__db.getCerts()
		self.__ckList = self.__db.getCookies()

	def __action(self, action):
		print "[BrowserMenu].__action :: action='%s'" %action
		fnc = self.__actionFuncs[self.__curMenu].get(action, None)
		if fnc != None:
			fnc()

	def __text(self):
		if self.__curMenu == self.MENU_SETTINGS:
			self.__cfgKeyText()
		elif self.__curMenu == self.MENU_BOOKMARKS:
			pass

	def __keyNumberGlobal(self, number):
		if self.__curMenu == self.MENU_SETTINGS:
			self.__cfgKeyNumberGlobal(number)
		elif self.__curMenu == self.MENU_BOOKMARKS:
			self.__bmKeyNumberGlobal(number)
		elif self.__curMenu == self.MENU_HISTORY:
			self.__hisKeyNumberGlobal(number)

	def __onMenuChanged(self):
		self.__bmFilterTimer.stop()
		self.__hisFilterTimer.stop()
		self.__dlRefreshTimer.stop()

		self.__curMenu = self.menu.getCurrent()[1]
		if self.__curMenu == self.MENU_BOOKMARKS:
			self.__showMenuList(True)
			self.__setButtons(_("Delete"), _("Add"), _("Edit"), _("Set as Startpage"))
			self.detailList.style = "default"
			self.__bmBuildList()
			self.detailInput.setText(self.__bmNeedle)
		elif self.__curMenu == self.MENU_HISTORY:
			self.__showMenuList(True)
			self.__setButtons(_("Clear"), "", "", _("Set as Startpage"))
			self.detailList.style = "history"
			self.__hisBuildList()
			self.detailInput.setText(self.__hisNeedle)
		elif self.__curMenu == self.MENU_SETTINGS:
			self.__showConfigList()
			self.__setButtons(_("Cancel"), _("Save"), "", "")
		elif self.__curMenu == self.MENU_DOWNLOADS:
			self.__showMenuList()
			self.__setButtons(_("Abort"), "", "", "")
			self.detailList.style = "downloads"
			self.__dlBuildList()
		elif self.__curMenu == self.MENU_CERTS:
			self.__showMenuList()
			self.__setButtons(_("Delete"), _("Details"), "", "")
			self.detailList.style = "certificates"
			self.__crtBuildList()
		elif self.__curMenu == self.MENU_COOKIES:
			self.__showMenuList()
			self.__setButtons(_("Delete"), "", "", _("Delete All"))
			self.detailList.style = "cookies"
			self.__ckBuildList()

	def __setButtons(self, red, green, yellow, blue):
		self.red.setText(red)
		self.__setButtonPixmapVisible(self["button_red"], red)
		self.green.setText(green)
		self.__setButtonPixmapVisible(self["button_green"], green)
		self.yellow.setText(yellow)
		self.__setButtonPixmapVisible(self["button_yellow"], yellow)
		self.blue.setText(blue)
		self.__setButtonPixmapVisible(self["button_blue"], blue)

	def __setButtonPixmapVisible(self, B, label):
		show = True
		if label == "":
			show = False
		B.setBoolean(show)

	def __showMenuList(self, hasFilter = False):
		if self.detailConfigList.visible:
			self.detailConfigList.hide()

# 		if not self.detailList.instance.visible:
# 			self.detailList.instance.show()
		if hasFilter:
			self.detailInput.show()
		else:
			self.detailInput.hide()

	def __showConfigList(self):
# 		if self.detailList.instance.visible == 1:
# 			self.detailList.instance.hide()
		self.detailInput.hide()
		if self.detailConfigList.visible == 0:
			self.detailConfigList.show()

	def __drawSeparator(self):
		self["line"].fill(0, 0, 4, BrowserMenu.height, 0xFF9900)
		self["line"].flush()

	def __setStatus(self, text):
		print "[BrowserMenu].__setStatus"
		self["statuslabel"].setText(text)
		self["statuslabel"].show()
		self.__statusTimer.startLongTimer(3)

	def __hideStatus(self):
		self["statuslabel"].hide()
		self.__statusTimer.stop()

	# Config List Methods
	def __cfgCreateSetup(self):
		list = [
			getConfigListEntry(_("Home Page"), config.plugins.WebBrowser.home),
			getConfigListEntry(_("Page to load on startup"), config.plugins.WebBrowser.startPage),
			getConfigListEntry(_("Search Provider"), config.plugins.WebBrowser.searchProvider),
			getConfigListEntry(_("Run fullscreen"), config.plugins.WebBrowser.fullscreen),
			getConfigListEntry(_("Offset in scroll mode (px)"), config.plugins.WebBrowser.scrollOffset),
			getConfigListEntry(_("Target directory for downloads"), config.plugins.WebBrowser.downloadpath),
			getConfigListEntry(_("Enable persistent storage"), config.plugins.WebBrowser.storage.enabled),
		]
		if config.plugins.WebBrowser.storage.enabled.value:
			list.append(getConfigListEntry(_("Path for persistent storage"), config.plugins.WebBrowser.storage.path))

		self.detailConfigList.setList(list)

	def __cfgExpandableElementChanged(self, element):
		self.__cfgCreateSetup()

	def __cfgSave(self):
		for x in self.detailConfigList.list:
			x[1].save()
		self.__setStatus(_("Settings have been saved successfully!"))

	def __cfgStoragePathChanged(self, element):
		action = [self.ACTION_STORAGE_PATH,True]
		if not action in self.__actions:
			self.__actions.append(action)

	def __cfgCancel(self):
		dlg = self.session.openWithCallback(self.__cfgCancelCB, MessageBox, _("Do you really want to discard all changes?"), type = MessageBox.TYPE_YESNO)
		dlg.setTitle(_("Discard changed settings?"))

	def __cfgCancelCB(self, confirmed):
		for x in self.detailConfigList.list:
			x[1].cancel()
		self.__setStatus(_("All changes to the settings have been discarded!"))

	def __cfgKeyText(self):
		from Screens.VirtualKeyBoard import VirtualKeyBoard
		self.session.openWithCallback(self.__cfgVirtualKeyBoardCallback, VirtualKeyBoard, title = self.detailConfigList.getCurrent()[0], text = self.detailConfigList.getCurrent()[1].getValue())

	def __cfgVirtualKeyBoardCallback(self, callback = None):
		if callback is not None and len(callback):
			self.detailConfigList.getCurrent()[1].setValue(callback)
			self.detailConfigList.invalidate(self.detailConfigList.getCurrent())

	def  __cfgKeyOK(self):
		self.detailConfigList.handleKey(KEY_OK)

	def  __cfgKeyUp(self):
		self.detailConfigList.instance.moveSelection(eListbox.moveUp)

	def  __cfgKeyDown(self):
		self.detailConfigList.instance.moveSelection(eListbox.moveDown)

	def  __cfgKeyLeft(self):
		self.detailConfigList.handleKey(KEY_LEFT)

	def __cfgKeyRight(self):
		self.detailConfigList.handleKey(KEY_RIGHT)

	def __cfgKeyHome(self):
		self.detailConfigList.handleKey(KEY_HOME)

	def __cfgKeyEnd(self):
		self.detailConfigList.handleKey(KEY_END)

	def __cfgKeyDelete(self):
		self.detailConfigList.handleKey(KEY_DELETE)

	def __cfgKeyBackspace(self):
		self.detailConfigList.handleKey(KEY_BACKSPACE)

	def __cfgKeyToggleOW(self):
		self.detailConfigList.handleKey(KEY_TOGGLEOW)

	def __cfgKeyAscii(self):
		self.detailConfigList.handleKey(KEY_ASCII)

	def __cfgKeyNumberGlobal(self, number):
		self.detailConfigList.handleKey(KEY_0 + number)

	#Bookmark List Methods
	def __bmOk(self):
		print "[BrowserMenu].__bmOk"
		if self.detailList.index > 0 and  self.detailList.getCurrent() != None:
			current = self.detailList.getCurrent()[0]
			print "[BrowserMenu].__bmOk, current = '%s'" %current
			self.__actions.append( (self.ACTION_BOOKMARK, current.url) )
			self.close( self.__actions )
		else:
			self.__bmAdd(Bookmark(-1, self.currentTitle, self.currentUrl))

	def __bmAdd(self, bookmark = None):
		self.session.openWithCallback(self.__bmEditCB, BookmarkEditor, bookmark)

	def __bmEdit(self):
		if self.detailList.index > 0 and  self.detailList.getCurrent() != None:
			cur = self.detailList.getCurrent()[0]
			self.session.openWithCallback(self.__bmEditCB, BookmarkEditor, cur)

	def __bmEditCB(self, bookmark):
		if bookmark != None:
			self.__db.setBookmark(bookmark)
			self.__bmReload()
			self.__setStatus(_("Bookmark '%s' saved succesfully!" %bookmark.name))

	def __bmDelete(self):
		if self.detailList.getCurrent() != None:
			name = self.detailList.getCurrent()[0].name
			print "[BrowserMenu].__bmDelete, name='%s'" %name
			dlg = self.session.openWithCallback( self.__bmDeleteCB, MessageBox, _("Do you really want to delete the bookmark '%s'?") %name, type = MessageBox.TYPE_YESNO )
			dlg.setTitle(_("Delete Bookmark?"))

	def __bmDeleteCB(self, confirmed):
		if confirmed:
			self.__db.deleteBookmark( self.detailList.getCurrent()[0] )
			name = self.detailList.getCurrent()[0]
			self.__setStatus(_("Bookmark '%s' deleted!" %name))
			self.__bmReload()

	def __bmSetCurrentAsHome(self):
		cur = self.detailList.getCurrent()[0]
		self.__setUrlAsHome(cur.url)

	def __bmGetEntryComponent(self, bookmark):
		return ( bookmark, bookmark.name, bookmark.url )

	def __bmBuildList(self):
		print "[BrowserMenu].__bmBuildList"
		list = []
		#Suggest current page for adding

		default = Bookmark(-2, _("Add '%s' to Bookmarks" %self.currentTitle), self.currentUrl)
		list.append(self.__bmGetEntryComponent(default))
		for b in self.__bmList:
			list.append(self.__bmGetEntryComponent(b))
		self.detailList.setList(list)

	def __bmReload(self, needle = ""):
		print "[BrowserMenu].__bmReload"
		self.__bmNeedle = needle
		self.__bmList = self.__db.getBookmarks(needle)
		self.__bmBuildList()

	def __bmFilterCB(self):
		print "[BrowserMenu].__bmFilterCB"
		needle = self.detailInput.getText()
		if needle != self.__bmNeedle:
			self.__bmReload(needle)
		else:
			self.__bmFilterTimer.stop()

	def __bmKeyNumberGlobal(self, number):
		self.detailInput.number(number)
		self.__bmFilterTimer.startLongTimer(1)

	def __bmKeyAscii(self):
		self.detailInput.handleAscii(getPrevAsciiCode())
		self.__bmFilterTimer.startLongTimer(1)

	def __bmKeyDelete(self):
		self.detailInput.delete()
		self.__bmFilterTimer.startLongTimer(1)

	def __bmKeyBackspace(self):
		self.detailInput.deleteBackward()
		self.__bmFilterTimer.startLongTimer(1)

	#History list methods
	def __hisSetCurrentAsHome(self):
		if self.detailList.getCurrent() != None:
			cur = self.detailList.getCurrent()[0]
			self.__setUrlAsHome(cur.url)

	def __setUrlAsHome(self, url):
		config.plugins.WebBrowser.home.value = url
		config.plugins.WebBrowser.home.save()
		self.__setStatus(_("Home page has been set to '%s'" %url))

	def __hisClear(self):
		dlg = self.session.openWithCallback(self.__hisClearCB, MessageBox, _("Do you really want to clear the History?"), type = MessageBox.TYPE_YESNO)
		dlg.setTitle(_("Clear History?"))

	def __hisClearCB(self, confirmed):
		if confirmed:
			self.__db.clearHistory()
			self.__hisReload()
			self.__setStatus(_("History cleared!"))

	def __hisGetEntryComponent(self, historyItem):
		date = strftime("%Y-%m-%d", localtime(historyItem.timestamp))
		time = strftime("%H:%M:%S", localtime(historyItem.timestamp))
		return ( historyItem, date, time, historyItem.title, historyItem.url )

	def __hisReload(self, needle = ""):
		print "[BrowserMenu].__hisReload"
		self.__hisNeedle = needle
		self.__hisList = self.__db.getHistory(needle)
		self.__hisBuildList()

	def __hisBuildList(self):
		print "[BrowserMenu].__hisBuildList"
		history = []
		for h in self.__hisList:
			history.append(self.__hisGetEntryComponent(h))
		self.detailList.setList(history)

	def __hisOk(self):
		if self.detailList.getCurrent() != None:
			current = self.detailList.getCurrent()[0]
			self.__actions.append( (self.ACTION_BOOKMARK, current.url) )
			self.close( self.__actions )

	def __hisFilterCB(self):
		needle = self.detailInput.getText()
		if needle != self.__hisNeedle:
			self.__hisReload(needle)
		else:
			self.__hisFilterTimer.stop()

	def __hisKeyNumberGlobal(self, number):
		self.detailInput.number(number)
		self.__hisFilterTimer.startLongTimer(1)

	def __hisKeyAscii(self):
		self.detailInput.handleAscii(getPrevAsciiCode())
		self.__hisFilterTimer.startLongTimer(1)

	def __hisKeyDelete(self):
		self.detailInput.delete()
		self.__hisFilterTimer.startLongTimer(1)

	def __hisKeyBackspace(self):
		self.detailInput.deleteBackward()
		self.__hisFilterTimer.startLongTimer(1)

	#Download list methods
	def __dlGetEntryComponent(self, job):
		return ( job, job.name, job.getStatustext(), int(100*job.progress/float(job.end)), str(100*job.progress/float(job.end)) + "%")

	def __dlBuildList(self):
		print "[BrowserMenu].__dlBuildList"
		downloads = []
		for job in downloadManager.getPendingJobs():
			downloads.append(self.__dlGetEntryComponent(job))
		self.detailList.setList(downloads)
		if not self.__dlRefreshTimer.isActive():
			self.__dlRefreshTimer.startLongTimer(3)

	def __dlAbort(self):
		print "[BrowserMenu].__dlAbort"
		cur = self.detailList.getCurrent()
		if cur != None:
			job = cur[0]
			dlg = self.session.openWithCallback( self.__dlAbortCB, MessageBox, _("Do you really want to abort downloading '%s'?") %job.name, type = MessageBox.TYPE_YESNO)
			dlg.setTitle(_("Abort Download?"))

	#Certificate list methods
	def __dlAbortCB(self, confirmed):
		if confirmed:
			self.detailList.getCurrent()[0].remove(downloadManager.jobDone)
			self.__dlBuildList()

	def __crtGetEntryComponent(self, cert):
		cn = "CN: %s" %(str(cert.cert.get_subject().commonName))
		return ( cert, str(cert.notBefore()), str(cert.notAfter()), str(cert.host), cn, str(cert.cert.digest("sha1")) )

	def __crtReload(self):
		print "[BrowserMenu].__crtReload"
		self.__crtList = self.__db.getCerts()
		self.__crtBuildList()


	def __crtBuildList(self):
		print "[BrowserMenu].__crtBuildList"
		certs = []
		for c in self.__crtList:
			certs.append(self.__crtGetEntryComponent(c))
		self.detailList.setList(certs)

	def __crtDelete(self):
		if self.detailList.index >= 0 and self.detailList.getCurrent() != None:
			cert = self.detailList.getCurrent()[0]
			print "[BrowserMenu].__crtDelete, host=%s,SHA1 fingerprint=%s" %(cert.host,cert.cert.digest("sha1"))
			text = _("Do you really want to remove the following certificate from the list of trusted certificates?\n\nHostname: %s\nSHA1-Fingerprint: %s") %(cert.host, cert.cert.digest("sha1"))
			dlg = self.session.openWithCallback( self.__crtDeleteCB, MessageBox, text, type = MessageBox.TYPE_YESNO )
			dlg.setTitle(_("Remove trusted certificate?"))

	def __crtDeleteCB(self, confirmed):
		print "[BrowserMenu].__crtDeleteCB"
		if confirmed:
			cert = self.detailList.getCurrent()[0]
			self.__db.deleteCert(cert)
			self.__crtReload()

	def __crtDetails(self):
		print "[BrowserMenu].__crtDetails"
		if self.detailList.index >= 0 and self.detailList.getCurrent() != None:
			cert = self.detailList.getCurrent()[0]

			text = _("Issued for:")
			for item in cert.cert.get_subject().get_components():
				text += "\n%s : %s" %(item[0], item[1])
			text += _("\n\nIssued from:")
			for item in cert.cert.get_issuer().get_components():
				text += "\n%s : %s" %(item[0], item[1])

			text += _("\n\nValidity:\n")
			text += _("From: %s\n") %cert.notBefore()
			text += _("Until: %s\n") %cert.notAfter()
			text += _("Expired: %s\n") %(_("Yes") if cert.cert.has_expired() else _("No"))

			dlg = self.session.open(MessageBox, text, type = MessageBox.TYPE_INFO)
			dlg.setTitle(_("Certificate Details (%s)") %cert.host)

	def __ckReload(self):
		print "[BrowserMenu].__ckReload"
		self.__ckList = self.__db.getCookies()
		self.__ckBuildList()

	def __ckBuildList(self):
		print "[BrowserMenu].__ckBuildList"
		cookies = []
		for c in self.__ckList:
			cookies.append(self.__ckGetEntryComponent(c))
		self.detailList.setList(cookies)

	def __ckGetEntryComponent(self, cookie):
		try:
			date = strftime("%Y-%m-%d", localtime(cookie.expires))
			time = strftime("%H:%M:%S", localtime(cookie.expires))
		except:
			date = _("never")
			time = _("never")
		return ( cookie, date, time, cookie.domain, cookie.path, cookie.raw )

	def __ckDelete(self):
		if self.detailList.index >= 0 and self.detailList.getCurrent() != None:
			cookie = self.detailList.getCurrent()[0]
			text = _("Do you really want to delete the following cookie?\nDomain: %s\nPath: %s\nKey: %s\nRaw-Content:\n%s") %(cookie.domain, cookie.path, cookie.key, cookie.raw)
			dlg = self.session.openWithCallback( self.__ckDeleteCB, MessageBox, text, type = MessageBox.TYPE_YESNO )
			dlg.setTitle(_("Delete Cookie?"))

	def __ckDeleteCB(self, confirmed):
		print "[BrowserMenu].__ckDeleteCB"
		if confirmed:
			self.__db.deleteCookie(self.detailList.getCurrent()[0])
			self.__ckReload()
			action = [self.ACTION_COOKIES,True]
			if not action in self.__actions:
				self.__actions.append(action)

	def __ckDeleteAll(self):
		if self.detailList.index >= 0 and self.detailList.getCurrent() != None:
			text = _("Do you really want to delete ALL cookies?")
			dlg = self.session.openWithCallback( self.__ckDeleteAllCB, MessageBox, text, type = MessageBox.TYPE_YESNO )
			dlg.setTitle(_("Delete Cookie?"))

	def __ckDeleteAllCB(self, confirmed):
		print "[BrowserMenu].__ckDeleteCB"
		if confirmed:
			self.__db.deleteAllCookies()
			self.__ckReload()
			action = [self.ACTION_COOKIES,True]
			if not action in self.__actions:
				self.__actions.append(action)
Ejemplo n.º 6
0
class BrowserMenu(Screen):
    ACTION_BOOKMARK = 0
    ACTION_COOKIES = 1
    ACTION_STORAGE_PATH = 2

    MENU_BOOKMARKS = 0
    MENU_SETTINGS = 1
    MENU_HISTORY = 2
    MENU_DOWNLOADS = 3
    MENU_CERTS = 4
    MENU_COOKIES = 5

    size = getDesktop(0).size()
    width = int(size.width() * 0.9)
    height = int(size.height() * 0.85)
    bof = height - 35  #Button-Offset

    skin = """
		<screen name="BrowserMenu" position="center,center" size="%(w)d,%(h)d" title="Web Browser - Menu" >
			<widget name="menu" position="0,0" zPosition="1" size="200,%(h)d" backgroundColor="#000000" transparent="1" />
			<widget source="line" render="Canvas" position="203,0" zPosition="2" size="4,%(h)d" backgroundColor="#000000" transparent="1" alphatest="on"/>
			<widget source="list" render="Listbox" position="210,0" zPosition="1" size="%(listW)d,%(listH)d" backgroundColor="#000000" transparent="1">
				<convert type="TemplatedMultiContent">
					{"templates":
						{"default": (55, [
							MultiContentEntryText(pos = (10, 1), size = (920, 25), font = 0, flags = RT_VALIGN_CENTER, text = 1),
							MultiContentEntryText(pos = (10, 30), size = (920, 25), font = 1, flags = RT_VALIGN_CENTER, text = 2),
						]),
						"history": (55, [
							MultiContentEntryText(pos = (10, 1), size = (150, 25), font = 1, flags = RT_VALIGN_CENTER, text = 1),
							MultiContentEntryText(pos = (10, 28), size = (150, 25), font = 1, flags = RT_VALIGN_CENTER, text = 2),
							MultiContentEntryText(pos = (190, 1), size = (690, 25), font = 0, flags = RT_VALIGN_CENTER, text = 3),
							MultiContentEntryText(pos = (190, 28), size = (690, 25), font = 1, flags = RT_VALIGN_CENTER, text = 4),
						]),
						"downloads": (25, [
							MultiContentEntryText(pos = (0, 1), size = (600, 24), font=1, flags = RT_HALIGN_LEFT, text = 1),
							MultiContentEntryText(pos = (610, 1), size = (150, 24), font=1, flags = RT_HALIGN_RIGHT, text = 2),
							MultiContentEntryProgress(pos = (760, 1), size = (100, 24), percent = 3),
							MultiContentEntryText(pos = (870, 1), size = (70, 24), font=1, flags = RT_HALIGN_RIGHT, text = 4),
						]),
						"certificates": (85, [
							MultiContentEntryText(pos = (10, 1), size = (150, 25), font = 1, flags = RT_VALIGN_CENTER, text = 1),
							MultiContentEntryText(pos = (10, 28), size = (150, 25), font = 1, flags = RT_VALIGN_CENTER, text = 2),
							MultiContentEntryText(pos = (190, 1), size = (690, 25), font = 0, flags = RT_VALIGN_CENTER, text = 3),
							MultiContentEntryText(pos = (190, 28), size = (690, 25), font = 1, flags = RT_VALIGN_CENTER, text = 4),
							MultiContentEntryText(pos = (10, 60), size = (900, 25), font = 0, flags = RT_VALIGN_CENTER, text = 5),
						]),
						"cookies": (75, [
							MultiContentEntryText(pos = (10, 1), size = (150, 25), font = 1, flags = RT_VALIGN_CENTER, text = 1),
							MultiContentEntryText(pos = (10, 28), size = (150, 25), font = 1, flags = RT_VALIGN_CENTER, text = 2),
							MultiContentEntryText(pos = (180, 1), size = (720, 25), font = 0, flags = RT_VALIGN_CENTER, text = 3),
							MultiContentEntryText(pos = (180, 28), size = (625, 25), font = 1, flags = RT_VALIGN_CENTER, text = 4),
							MultiContentEntryText(pos = (10, 60), size = (900, 15), font = 2, flags = RT_VALIGN_CENTER, text = 5),
						])
						},
					"fonts": [gFont("Regular", 22), gFont("Regular", 16), gFont("Regular", 13)]
					}
				</convert>
			</widget>
			<widget name="statuslabel" position="210,%(inputY)d" size="%(listW)d,25" font="Regular;20"  zPosition="2" halign="center" valign="center" backgroundColor="#000000" transparent="0" />
			<widget name="input" position="210,%(inputY)d" zPosition="1" size="%(listW)d,25" font="Regular;20" halign="left" valign="bottom" backgroundColor="#000000" transparent="1"/>
			<widget name="config" position="210,0" zPosition="2" size="%(listW)d,%(configH)d" backgroundColor="background" transparent="0" />

			<ePixmap pixmap="skin_default/buttons/button_red_off.png" position="210,%(btnY)d" size="15,16" alphatest="on" />
			<widget source="button_red" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_red.png" position="210,%(btnY)d" size="15,16" alphatest="on">
				<convert type="ConditionalShowHide" />
			</widget>
			<widget name="red" position="230,%(btnTxtY)d" size="100,20" foregroundColor="white" backgroundColor="background" font="Regular;18" transparent="1" halign="left" valign="top"/>

			<ePixmap pixmap="skin_default/buttons/button_green_off.png" position="340,%(btnY)d" size="15,16" zPosition="1" alphatest="on" />
			<widget source="button_green" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_green.png" position="340,%(btnY)d" size="15,16" alphatest="on">
				<convert type="ConditionalShowHide" />
			</widget>
			<widget name="green" position="360,%(btnTxtY)d" size="100,20" foregroundColor="white" backgroundColor="background" font="Regular;18" transparent="1" halign="left" valign="top"/>

			<ePixmap pixmap="skin_default/buttons/button_yellow_off.png" position="470,%(btnY)d" size="15,16" alphatest="on" />
			<widget source="button_yellow" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_yellow.png" position="470,%(btnY)d" size="15,16" alphatest="on">
				<convert type="ConditionalShowHide" />
			</widget>
			<widget name="yellow" position="490,%(btnTxtY)d" size="100,20" foregroundColor="white" backgroundColor="background" font="Regular;18" transparent="1" halign="left" valign="top"/>

			<ePixmap pixmap="skin_default/buttons/button_blue_off.png" position="600,%(btnY)d" size="15,16" alphatest="on" />
			<widget source="button_blue" zPosition="2" render="Pixmap" pixmap="skin_default/buttons/button_blue.png" position="600,%(btnY)d" size="15,16" alphatest="on">
				<convert type="ConditionalShowHide" />
			</widget>
			<widget name="blue" position="620,%(btnTxtY)d" size="200,20" foregroundColor="white" backgroundColor="background" font="Regular;18" transparent="1" halign="left" valign="top"/>
		</screen>
		""" % {
        "w": width,
        "h": height,
        "listW": width - 210,
        "listH": height - 90,
        "inputY": height - 80,
        "configH": height - 90,
        "btnY": bof + 2,
        "btnTxtY": bof
    }

    def __init__(self, session, currentTitle, currentUrl, menulist=None):
        Screen.__init__(self, session)

        self.currentUrl = currentUrl
        self.currentTitle = currentTitle

        #Menu
        if menulist is None:
            self.menu = MenuList([
                (_("Bookmarks"), self.MENU_BOOKMARKS),
                (_("History"), self.MENU_HISTORY),
                (_("Downloads"), self.MENU_DOWNLOADS),
                (_("Certificates"), self.MENU_CERTS),
                (_("Cookies"), self.MENU_COOKIES),
                (_("Settings"), self.MENU_SETTINGS),
            ],
                                 enableWrapAround=True)
        else:
            self.menu = MenuList(menulist, enableWrapAround=True)
        self["menu"] = self.menu

        self["statuslabel"] = Label("")
        self["statuslabel"].hide()

        #Color Buttons
        self["button_red"] = Boolean(False)
        self["button_green"] = Boolean(False)
        self["button_yellow"] = Boolean(False)
        self["button_blue"] = Boolean(False)
        self.red = Label("")
        self.green = Label("")
        self.yellow = Label("")
        self.blue = Label("")
        self["red"] = self.red
        self["green"] = self.green
        self["yellow"] = self.yellow
        self["blue"] = self.blue

        #Lists
        self.detailList = List([], enableWrapAround=True)
        self.detailConfigList = ConfigList([])
        self.detailConfigList.l.setSeperation((BrowserMenu.width - 210) / 2)
        config.plugins.WebBrowser.storage.enabled.addNotifier(
            self.__cfgExpandableElementChanged, initial_call=False)
        config.plugins.WebBrowser.storage.enabled.addNotifier(
            self.__cfgStoragePathChanged, initial_call=False)
        config.plugins.WebBrowser.storage.path.addNotifier(
            self.__cfgStoragePathChanged, initial_call=False)

        self.detailInput = EnhancedInput()

        self["list"] = self.detailList
        self["config"] = self.detailConfigList
        self["input"] = self.detailInput
        self["line"] = CanvasSource()

        self.__cfgCreateSetup()

        self.__db = BrowserDB.getInstance()
        self.__curMenu = self.MENU_BOOKMARKS
        self.__bmList = None
        self.__hisList = None
        self.__crtList = None
        self.__ckList = None
        self.__bmNeedle = ""
        self.__bmFilterTimer = eTimer()
        self.__bmFilterTimer_conn = self.__bmFilterTimer.timeout.connect(
            self.__bmFilterCB)
        self.__hisNeedle = ""
        self.__hisFilterTimer = eTimer()
        self.__hisFilterTimer_conn = self.__hisFilterTimer.timeout.connect(
            self.__hisFilterCB)
        self.__dlRefreshTimer = eTimer()
        self.__dlRefreshTimer_conn = self.__dlRefreshTimer.timeout.connect(
            self.__dlBuildList)
        self.__statusTimer = eTimer()
        self.__statusTimer_conn = self.__statusTimer.timeout.connect(
            self.__hideStatus)
        self.__actions = []

        self.onFirstExecBegin.append(self.__drawSeparator)
        self.onFirstExecBegin.append(self.__onMenuChanged)
        self.onExecBegin.append(self.__reloadData)
        self.onShow.append(self.setKeyboardModeAscii)

        self["actions"] = ActionMap(
            ["BrowserActions", "ColorActions"],
            {
                "ok": self.__actionOk,
                "enter": self.__actionOk,
                "exit": self.__actionExit,
                "pageUp": self.__actionMenuUp,
                "pageDown": self.__actionMenuDown,
                "up": boundFunction(self.__action, "up"),
                "down": boundFunction(self.__action, "down"),
                "left": boundFunction(self.__action, "left"),
                "right": boundFunction(self.__action, "right"),
                "red": boundFunction(self.__action, "red"),
                "green": boundFunction(self.__action, "green"),
                "yellow": boundFunction(self.__action, "yellow"),
                "blue": boundFunction(self.__action, "blue"),
                "backspace": boundFunction(self.__action, "backspace"),
                "delete": boundFunction(self.__action, "delete"),
                "ascii": boundFunction(self.__action, "ascii"),
                # TODO "text" : self.__text
            },
            -2)

        self["numberactions"] = NumberActionMap(
            ["NumberActions"], {
                "1": self.__keyNumberGlobal,
                "2": self.__keyNumberGlobal,
                "3": self.__keyNumberGlobal,
                "4": self.__keyNumberGlobal,
                "5": self.__keyNumberGlobal,
                "6": self.__keyNumberGlobal,
                "7": self.__keyNumberGlobal,
                "8": self.__keyNumberGlobal,
                "9": self.__keyNumberGlobal,
                "0": self.__keyNumberGlobal
            }, -2)

        self.__actionFuncs = {
            self.MENU_BOOKMARKS: {
                "up": self.detailList.selectPrevious,
                "down": self.detailList.selectNext,
                "left": self.detailList.selectPrevious,
                "right": self.detailList.pageDown,
                "ok": self.__bmOk,
                "enter": self.__bmOk,
                "red": self.__bmDelete,
                "green": self.__bmAdd,
                "yellow": self.__bmEdit,
                "blue": self.__bmSetCurrentAsHome,
                "backspace": self.__bmKeyBackspace,
                "delete": self.__bmKeyDelete,
                "ascii": self.__bmKeyAscii,
            },
            self.MENU_HISTORY: {
                "up": self.detailList.selectPrevious,
                "down": self.detailList.selectNext,
                "left": self.detailList.pageUp,
                "right": self.detailList.pageDown,
                "ok": self.__hisOk,
                "enter": self.__hisOk,
                "red": self.__hisClear,
                "blue": self.__hisSetCurrentAsHome,
                "backspace": self.__hisKeyBackspace,
                "delete": self.__hisKeyDelete,
                "ascii": self.__hisKeyAscii,
            },
            self.MENU_SETTINGS: {
                "up": self.__cfgKeyUp,
                "down": self.__cfgKeyDown,
                "left": self.__cfgKeyLeft,
                "right": self.__cfgKeyRight,
                "ok": self.__cfgKeyOK,
                "enter": self.__cfgKeyOK,
                "red": self.__cfgCancel,
                "green": self.__cfgSave,
                "backspace": self.__cfgKeyBackspace,
                "delete": self.__cfgKeyDelete,
                "ascii": self.__cfgKeyAscii,
            },
            self.MENU_DOWNLOADS: {
                "up": self.detailList.selectPrevious,
                "down": self.detailList.selectNext,
                "left": self.detailList.pageUp,
                "right": self.detailList.pageDown,
                "red": self.__dlAbort,
            },
            self.MENU_CERTS: {
                "up": self.detailList.selectPrevious,
                "down": self.detailList.selectNext,
                "left": self.detailList.pageUp,
                "right": self.detailList.pageDown,
                "red": self.__crtDelete,
                "green": self.__crtDetails,
            },
            self.MENU_COOKIES: {
                "up": self.detailList.selectPrevious,
                "down": self.detailList.selectNext,
                "left": self.detailList.pageUp,
                "right": self.detailList.pageDown,
                "red": self.__ckDelete,
                "blue": self.__ckDeleteAll,
            }
        }

    def _close(self):
        config.plugins.WebBrowser.storage.enabled.removeNotifier(
            self.__cfgExpandableElementChanged)
        config.plugins.WebBrowser.storage.enabled.removeNotifier(
            self.__cfgStoragePathChanged)
        config.plugins.WebBrowser.storage.path.removeNotifier(
            self.__cfgStoragePathChanged)
        self.close(self.__actions)

    def __actionOk(self):
        if self["statuslabel"].visible:
            self["statuslabel"].hide()
        else:
            self.__action("ok")

    def __actionExit(self):
        if self["statuslabel"].visible:
            self["statuslabel"].hide()
        else:
            if self.detailConfigList.isChanged():
                self.__cfgSave()
            self._close()

    def __actionMenuUp(self):
        self.menu.up()
        self.__onMenuChanged()

    def __actionMenuDown(self):
        self.menu.down()
        self.__onMenuChanged()

    def __reloadData(self):
        self.__bmList = self.__db.getBookmarks()
        self.__hisList = self.__db.getHistory()
        self.__crtList = self.__db.getCerts()
        self.__ckList = self.__db.getCookies()

    def __action(self, action):
        print "[BrowserMenu].__action :: action='%s'" % action
        fnc = self.__actionFuncs[self.__curMenu].get(action, None)
        if fnc != None:
            fnc()

    def __text(self):
        if self.__curMenu == self.MENU_SETTINGS:
            self.__cfgKeyText()
        elif self.__curMenu == self.MENU_BOOKMARKS:
            pass

    def __keyNumberGlobal(self, number):
        if self.__curMenu == self.MENU_SETTINGS:
            self.__cfgKeyNumberGlobal(number)
        elif self.__curMenu == self.MENU_BOOKMARKS:
            self.__bmKeyNumberGlobal(number)
        elif self.__curMenu == self.MENU_HISTORY:
            self.__hisKeyNumberGlobal(number)

    def __onMenuChanged(self):
        self.__bmFilterTimer.stop()
        self.__hisFilterTimer.stop()
        self.__dlRefreshTimer.stop()

        self.__curMenu = self.menu.getCurrent()[1]
        if self.__curMenu == self.MENU_BOOKMARKS:
            self.__showMenuList(True)
            self.__setButtons(_("Delete"), _("Add"), _("Edit"),
                              _("Set as Startpage"))
            self.detailList.style = "default"
            self.__bmBuildList()
            self.detailInput.setText(self.__bmNeedle)
        elif self.__curMenu == self.MENU_HISTORY:
            self.__showMenuList(True)
            self.__setButtons(_("Clear"), "", "", _("Set as Startpage"))
            self.detailList.style = "history"
            self.__hisBuildList()
            self.detailInput.setText(self.__hisNeedle)
        elif self.__curMenu == self.MENU_SETTINGS:
            self.__showConfigList()
            self.__setButtons(_("Cancel"), _("Save"), "", "")
        elif self.__curMenu == self.MENU_DOWNLOADS:
            self.__showMenuList()
            self.__setButtons(_("Abort"), "", "", "")
            self.detailList.style = "downloads"
            self.__dlBuildList()
        elif self.__curMenu == self.MENU_CERTS:
            self.__showMenuList()
            self.__setButtons(_("Delete"), _("Details"), "", "")
            self.detailList.style = "certificates"
            self.__crtBuildList()
        elif self.__curMenu == self.MENU_COOKIES:
            self.__showMenuList()
            self.__setButtons(_("Delete"), "", "", _("Delete All"))
            self.detailList.style = "cookies"
            self.__ckBuildList()

    def __setButtons(self, red, green, yellow, blue):
        self.red.setText(red)
        self.__setButtonPixmapVisible(self["button_red"], red)
        self.green.setText(green)
        self.__setButtonPixmapVisible(self["button_green"], green)
        self.yellow.setText(yellow)
        self.__setButtonPixmapVisible(self["button_yellow"], yellow)
        self.blue.setText(blue)
        self.__setButtonPixmapVisible(self["button_blue"], blue)

    def __setButtonPixmapVisible(self, B, label):
        show = True
        if label == "":
            show = False
        B.setBoolean(show)

    def __showMenuList(self, hasFilter=False):
        if self.detailConfigList.visible:
            self.detailConfigList.hide()

# 		if not self.detailList.instance.visible:
# 			self.detailList.instance.show()
        if hasFilter:
            self.detailInput.show()
        else:
            self.detailInput.hide()

    def __showConfigList(self):
        # 		if self.detailList.instance.visible == 1:
        # 			self.detailList.instance.hide()
        self.detailInput.hide()
        if self.detailConfigList.visible == 0:
            self.detailConfigList.show()

    def __drawSeparator(self):
        self["line"].fill(0, 0, 4, BrowserMenu.height, 0xFF9900)
        self["line"].flush()

    def __setStatus(self, text):
        print "[BrowserMenu].__setStatus"
        self["statuslabel"].setText(text)
        self["statuslabel"].show()
        self.__statusTimer.startLongTimer(3)

    def __hideStatus(self):
        self["statuslabel"].hide()
        self.__statusTimer.stop()

    # Config List Methods
    def __cfgCreateSetup(self):
        list = [
            getConfigListEntry(_("Home Page"), config.plugins.WebBrowser.home),
            getConfigListEntry(_("Page to load on startup"),
                               config.plugins.WebBrowser.startPage),
            getConfigListEntry(_("Search Provider"),
                               config.plugins.WebBrowser.searchProvider),
            getConfigListEntry(_("Run fullscreen"),
                               config.plugins.WebBrowser.fullscreen),
            getConfigListEntry(_("Offset in scroll mode (px)"),
                               config.plugins.WebBrowser.scrollOffset),
            getConfigListEntry(_("Target directory for downloads"),
                               config.plugins.WebBrowser.downloadpath),
            getConfigListEntry(_("Enable persistent storage"),
                               config.plugins.WebBrowser.storage.enabled),
        ]
        if config.plugins.WebBrowser.storage.enabled.value:
            list.append(
                getConfigListEntry(_("Path for persistent storage"),
                                   config.plugins.WebBrowser.storage.path))

        self.detailConfigList.setList(list)

    def __cfgExpandableElementChanged(self, element):
        self.__cfgCreateSetup()

    def __cfgSave(self):
        for x in self.detailConfigList.list:
            x[1].save()
        self.__setStatus(_("Settings have been saved successfully!"))

    def __cfgStoragePathChanged(self, element):
        action = [self.ACTION_STORAGE_PATH, True]
        if not action in self.__actions:
            self.__actions.append(action)

    def __cfgCancel(self):
        dlg = self.session.openWithCallback(
            self.__cfgCancelCB,
            MessageBox,
            _("Do you really want to discard all changes?"),
            type=MessageBox.TYPE_YESNO)
        dlg.setTitle(_("Discard changed settings?"))

    def __cfgCancelCB(self, confirmed):
        for x in self.detailConfigList.list:
            x[1].cancel()
        self.__setStatus(_("All changes to the settings have been discarded!"))

    def __cfgKeyText(self):
        from Screens.VirtualKeyBoard import VirtualKeyBoard
        self.session.openWithCallback(
            self.__cfgVirtualKeyBoardCallback,
            VirtualKeyBoard,
            title=self.detailConfigList.getCurrent()[0],
            text=self.detailConfigList.getCurrent()[1].getValue())

    def __cfgVirtualKeyBoardCallback(self, callback=None):
        if callback is not None and len(callback):
            self.detailConfigList.getCurrent()[1].setValue(callback)
            self.detailConfigList.invalidate(
                self.detailConfigList.getCurrent())

    def __cfgKeyOK(self):
        self.detailConfigList.handleKey(KEY_OK)

    def __cfgKeyUp(self):
        self.detailConfigList.instance.moveSelection(eListbox.moveUp)

    def __cfgKeyDown(self):
        self.detailConfigList.instance.moveSelection(eListbox.moveDown)

    def __cfgKeyLeft(self):
        self.detailConfigList.handleKey(KEY_LEFT)

    def __cfgKeyRight(self):
        self.detailConfigList.handleKey(KEY_RIGHT)

    def __cfgKeyHome(self):
        self.detailConfigList.handleKey(KEY_HOME)

    def __cfgKeyEnd(self):
        self.detailConfigList.handleKey(KEY_END)

    def __cfgKeyDelete(self):
        self.detailConfigList.handleKey(KEY_DELETE)

    def __cfgKeyBackspace(self):
        self.detailConfigList.handleKey(KEY_BACKSPACE)

    def __cfgKeyToggleOW(self):
        self.detailConfigList.handleKey(KEY_TOGGLEOW)

    def __cfgKeyAscii(self):
        self.detailConfigList.handleKey(KEY_ASCII)

    def __cfgKeyNumberGlobal(self, number):
        self.detailConfigList.handleKey(KEY_0 + number)

    #Bookmark List Methods
    def __bmOk(self):
        print "[BrowserMenu].__bmOk"
        if self.detailList.index > 0 and self.detailList.getCurrent() != None:
            current = self.detailList.getCurrent()[0]
            print "[BrowserMenu].__bmOk, current = '%s'" % current
            self.__actions.append((self.ACTION_BOOKMARK, current.url))
            self.close(self.__actions)
        else:
            self.__bmAdd(Bookmark(-1, self.currentTitle, self.currentUrl))

    def __bmAdd(self, bookmark=None):
        self.session.openWithCallback(self.__bmEditCB, BookmarkEditor,
                                      bookmark)

    def __bmEdit(self):
        if self.detailList.index > 0 and self.detailList.getCurrent() != None:
            cur = self.detailList.getCurrent()[0]
            self.session.openWithCallback(self.__bmEditCB, BookmarkEditor, cur)

    def __bmEditCB(self, bookmark):
        if bookmark != None:
            self.__db.setBookmark(bookmark)
            self.__bmReload()
            self.__setStatus(
                _("Bookmark '%s' saved succesfully!" % bookmark.name))

    def __bmDelete(self):
        if self.detailList.getCurrent() != None:
            name = self.detailList.getCurrent()[0].name
            print "[BrowserMenu].__bmDelete, name='%s'" % name
            dlg = self.session.openWithCallback(
                self.__bmDeleteCB,
                MessageBox,
                _("Do you really want to delete the bookmark '%s'?") % name,
                type=MessageBox.TYPE_YESNO)
            dlg.setTitle(_("Delete Bookmark?"))

    def __bmDeleteCB(self, confirmed):
        if confirmed:
            self.__db.deleteBookmark(self.detailList.getCurrent()[0])
            name = self.detailList.getCurrent()[0]
            self.__setStatus(_("Bookmark '%s' deleted!" % name))
            self.__bmReload()

    def __bmSetCurrentAsHome(self):
        cur = self.detailList.getCurrent()[0]
        self.__setUrlAsHome(cur.url)

    def __bmGetEntryComponent(self, bookmark):
        return (bookmark, bookmark.name, bookmark.url)

    def __bmBuildList(self):
        print "[BrowserMenu].__bmBuildList"
        list = []
        #Suggest current page for adding

        default = Bookmark(-2, _("Add '%s' to Bookmarks" % self.currentTitle),
                           self.currentUrl)
        list.append(self.__bmGetEntryComponent(default))
        for b in self.__bmList:
            list.append(self.__bmGetEntryComponent(b))
        self.detailList.setList(list)

    def __bmReload(self, needle=""):
        print "[BrowserMenu].__bmReload"
        self.__bmNeedle = needle
        self.__bmList = self.__db.getBookmarks(needle)
        self.__bmBuildList()

    def __bmFilterCB(self):
        print "[BrowserMenu].__bmFilterCB"
        needle = self.detailInput.getText()
        if needle != self.__bmNeedle:
            self.__bmReload(needle)
        else:
            self.__bmFilterTimer.stop()

    def __bmKeyNumberGlobal(self, number):
        self.detailInput.number(number)
        self.__bmFilterTimer.startLongTimer(1)

    def __bmKeyAscii(self):
        self.detailInput.handleAscii(getPrevAsciiCode())
        self.__bmFilterTimer.startLongTimer(1)

    def __bmKeyDelete(self):
        self.detailInput.delete()
        self.__bmFilterTimer.startLongTimer(1)

    def __bmKeyBackspace(self):
        self.detailInput.deleteBackward()
        self.__bmFilterTimer.startLongTimer(1)

    #History list methods
    def __hisSetCurrentAsHome(self):
        if self.detailList.getCurrent() != None:
            cur = self.detailList.getCurrent()[0]
            self.__setUrlAsHome(cur.url)

    def __setUrlAsHome(self, url):
        config.plugins.WebBrowser.home.value = url
        config.plugins.WebBrowser.home.save()
        self.__setStatus(_("Home page has been set to '%s'" % url))

    def __hisClear(self):
        dlg = self.session.openWithCallback(
            self.__hisClearCB,
            MessageBox,
            _("Do you really want to clear the History?"),
            type=MessageBox.TYPE_YESNO)
        dlg.setTitle(_("Clear History?"))

    def __hisClearCB(self, confirmed):
        if confirmed:
            self.__db.clearHistory()
            self.__hisReload()
            self.__setStatus(_("History cleared!"))

    def __hisGetEntryComponent(self, historyItem):
        date = strftime("%Y-%m-%d", localtime(historyItem.timestamp))
        time = strftime("%H:%M:%S", localtime(historyItem.timestamp))
        return (historyItem, date, time, historyItem.title, historyItem.url)

    def __hisReload(self, needle=""):
        print "[BrowserMenu].__hisReload"
        self.__hisNeedle = needle
        self.__hisList = self.__db.getHistory(needle)
        self.__hisBuildList()

    def __hisBuildList(self):
        print "[BrowserMenu].__hisBuildList"
        history = []
        for h in self.__hisList:
            history.append(self.__hisGetEntryComponent(h))
        self.detailList.setList(history)

    def __hisOk(self):
        if self.detailList.getCurrent() != None:
            current = self.detailList.getCurrent()[0]
            self.__actions.append((self.ACTION_BOOKMARK, current.url))
            self.close(self.__actions)

    def __hisFilterCB(self):
        needle = self.detailInput.getText()
        if needle != self.__hisNeedle:
            self.__hisReload(needle)
        else:
            self.__hisFilterTimer.stop()

    def __hisKeyNumberGlobal(self, number):
        self.detailInput.number(number)
        self.__hisFilterTimer.startLongTimer(1)

    def __hisKeyAscii(self):
        self.detailInput.handleAscii(getPrevAsciiCode())
        self.__hisFilterTimer.startLongTimer(1)

    def __hisKeyDelete(self):
        self.detailInput.delete()
        self.__hisFilterTimer.startLongTimer(1)

    def __hisKeyBackspace(self):
        self.detailInput.deleteBackward()
        self.__hisFilterTimer.startLongTimer(1)

    #Download list methods
    def __dlGetEntryComponent(self, job):
        return (job, job.name, job.getStatustext(),
                int(100 * job.progress / float(job.end)),
                str(100 * job.progress / float(job.end)) + "%")

    def __dlBuildList(self):
        print "[BrowserMenu].__dlBuildList"
        downloads = []
        for job in downloadManager.getPendingJobs():
            downloads.append(self.__dlGetEntryComponent(job))
        self.detailList.setList(downloads)
        if not self.__dlRefreshTimer.isActive():
            self.__dlRefreshTimer.startLongTimer(3)

    def __dlAbort(self):
        print "[BrowserMenu].__dlAbort"
        cur = self.detailList.getCurrent()
        if cur != None:
            job = cur[0]
            dlg = self.session.openWithCallback(
                self.__dlAbortCB,
                MessageBox,
                _("Do you really want to abort downloading '%s'?") % job.name,
                type=MessageBox.TYPE_YESNO)
            dlg.setTitle(_("Abort Download?"))

    #Certificate list methods
    def __dlAbortCB(self, confirmed):
        if confirmed:
            self.detailList.getCurrent()[0].remove(downloadManager.jobDone)
            self.__dlBuildList()

    def __crtGetEntryComponent(self, cert):
        cn = "CN: %s" % (str(cert.cert.get_subject().commonName))
        return (cert, str(cert.notBefore()), str(cert.notAfter()),
                str(cert.host), cn, str(cert.cert.digest("sha1")))

    def __crtReload(self):
        print "[BrowserMenu].__crtReload"
        self.__crtList = self.__db.getCerts()
        self.__crtBuildList()

    def __crtBuildList(self):
        print "[BrowserMenu].__crtBuildList"
        certs = []
        for c in self.__crtList:
            certs.append(self.__crtGetEntryComponent(c))
        self.detailList.setList(certs)

    def __crtDelete(self):
        if self.detailList.index >= 0 and self.detailList.getCurrent() != None:
            cert = self.detailList.getCurrent()[0]
            print "[BrowserMenu].__crtDelete, host=%s,SHA1 fingerprint=%s" % (
                cert.host, cert.cert.digest("sha1"))
            text = _(
                "Do you really want to remove the following certificate from the list of trusted certificates?\n\nHostname: %s\nSHA1-Fingerprint: %s"
            ) % (cert.host, cert.cert.digest("sha1"))
            dlg = self.session.openWithCallback(self.__crtDeleteCB,
                                                MessageBox,
                                                text,
                                                type=MessageBox.TYPE_YESNO)
            dlg.setTitle(_("Remove trusted certificate?"))

    def __crtDeleteCB(self, confirmed):
        print "[BrowserMenu].__crtDeleteCB"
        if confirmed:
            cert = self.detailList.getCurrent()[0]
            self.__db.deleteCert(cert)
            self.__crtReload()

    def __crtDetails(self):
        print "[BrowserMenu].__crtDetails"
        if self.detailList.index >= 0 and self.detailList.getCurrent() != None:
            cert = self.detailList.getCurrent()[0]

            text = _("Issued for:")
            for item in cert.cert.get_subject().get_components():
                text += "\n%s : %s" % (item[0], item[1])
            text += _("\n\nIssued from:")
            for item in cert.cert.get_issuer().get_components():
                text += "\n%s : %s" % (item[0], item[1])

            text += _("\n\nValidity:\n")
            text += _("From: %s\n") % cert.notBefore()
            text += _("Until: %s\n") % cert.notAfter()
            text += _("Expired: %s\n") % (_("Yes") if cert.cert.has_expired()
                                          else _("No"))

            dlg = self.session.open(MessageBox,
                                    text,
                                    type=MessageBox.TYPE_INFO)
            dlg.setTitle(_("Certificate Details (%s)") % cert.host)

    def __ckReload(self):
        print "[BrowserMenu].__ckReload"
        self.__ckList = self.__db.getCookies()
        self.__ckBuildList()

    def __ckBuildList(self):
        print "[BrowserMenu].__ckBuildList"
        cookies = []
        for c in self.__ckList:
            cookies.append(self.__ckGetEntryComponent(c))
        self.detailList.setList(cookies)

    def __ckGetEntryComponent(self, cookie):
        try:
            date = strftime("%Y-%m-%d", localtime(cookie.expires))
            time = strftime("%H:%M:%S", localtime(cookie.expires))
        except:
            date = _("never")
            time = _("never")
        return (cookie, date, time, cookie.domain, cookie.path, cookie.raw)

    def __ckDelete(self):
        if self.detailList.index >= 0 and self.detailList.getCurrent() != None:
            cookie = self.detailList.getCurrent()[0]
            text = _(
                "Do you really want to delete the following cookie?\nDomain: %s\nPath: %s\nKey: %s\nRaw-Content:\n%s"
            ) % (cookie.domain, cookie.path, cookie.key, cookie.raw)
            dlg = self.session.openWithCallback(self.__ckDeleteCB,
                                                MessageBox,
                                                text,
                                                type=MessageBox.TYPE_YESNO)
            dlg.setTitle(_("Delete Cookie?"))

    def __ckDeleteCB(self, confirmed):
        print "[BrowserMenu].__ckDeleteCB"
        if confirmed:
            self.__db.deleteCookie(self.detailList.getCurrent()[0])
            self.__ckReload()
            action = [self.ACTION_COOKIES, True]
            if not action in self.__actions:
                self.__actions.append(action)

    def __ckDeleteAll(self):
        if self.detailList.index >= 0 and self.detailList.getCurrent() != None:
            text = _("Do you really want to delete ALL cookies?")
            dlg = self.session.openWithCallback(self.__ckDeleteAllCB,
                                                MessageBox,
                                                text,
                                                type=MessageBox.TYPE_YESNO)
            dlg.setTitle(_("Delete Cookie?"))

    def __ckDeleteAllCB(self, confirmed):
        print "[BrowserMenu].__ckDeleteCB"
        if confirmed:
            self.__db.deleteAllCookies()
            self.__ckReload()
            action = [self.ACTION_COOKIES, True]
            if not action in self.__actions:
                self.__actions.append(action)
Ejemplo n.º 7
0
class LastFMScreenMain(Screen,HelpableScreen,LastFM):
    skin = """
        <screen position="110,83" size="530,430" title="Last.FM" >
            
            <widget name="artist" position="0,0" size="70,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />          
            <widget name="album" position="0,40" size="70,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />          
            <widget name="track" position="0,80" size="70,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />          
            
            <widget name="info_artist" position="70,0" size="284,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />          
            <widget name="duration" position="354,0" size="60,30" valign=\"center\" halign=\"right\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />          
            <widget name="info_album" position="70,40" size="344,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />          
            <widget name="info_track" position="70,80" size="344,30" valign=\"center\" halign=\"left\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />          
            <widget name="info_cover" position="414,0" size="116,116" />          
            
            <widget name="tablist" position="0,120" size="150,260" scrollbarMode="showOnDemand" />            
            <widget name="streamlist" position="150,120" size="380,260" scrollbarMode="showOnDemand" />            
            
            <widget name="button_red" position="10,400" size="60,30" backgroundColor=\"red\" valign=\"center\" halign=\"center\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />          
            <widget name="button_green" position="80,400" size="60,30" backgroundColor=\"green\" valign=\"center\" halign=\"center\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\"/>            
            <widget name="button_yellow" position="150,400" size="60,30" backgroundColor=\"yellow\" valign=\"center\" halign=\"center\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />            
            <widget name="button_blue" position="220,400" size="60,30" backgroundColor=\"blue\" valign=\"center\" halign=\"center\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />            
            <widget name="infolabel" position="290,400" size="290,30" valign=\"center\" halign=\"center\" zPosition=\"2\"  foregroundColor=\"white\" font=\"Regular;18\" />           
        </screen>"""
         
    noCoverArtPNG = "/usr/share/enigma2/skin_default/no_coverArt.png"
    
    def __init__(self, session,streamplayer, args = 0):
        self.skin = LastFMScreenMain.skin
        Screen.__init__(self, session)
        HelpableScreen.__init__(self)
        LastFM.__init__(self)
        self.session = session
        self.streamplayer = streamplayer#StreamPlayer(session)
        self.streamplayer.onStateChanged.append(self.onStreamplayerStateChanged)
        self.imageconverter = ImageConverter(116,116,self.setCoverArt)
        Screen.__init__(self, session)
        
        self.tabs=[("personal Stations",self.loadPersonalStations)
                   ,("Global Tags",self.loadGlobalTags)
                   ,("Top Tracks",self.loadTopTracks)
                   ,("Recent Tracks",self.loadRecentTracks)
                   ,("Loved Tracks",self.loadLovedTracks)
                   ,("Banned Tracks",self.loadBannedTracks)
                   ,("Friends",self.loadFriends)
                   ,("Neighbours",self.loadNeighbours)
                   ]
        tablist =[]
        for tab in self.tabs:
            tablist.append((tab[0],tab))
        self.tablist = MenuList(tablist)
        self.tablist.onSelectionChanged.append(self.action_TabChanged)
        
        self["artist"] = Label(_("Artist")+":")
        self["duration"] = Label("-00:00")
        self["album"] = Label(_("Album")+":")
        self["track"] = Label(_("Track")+":")
        
        self["info_artist"] = Label("N/A")
        self["info_album"] = Label("N/A")
        self["info_track"] = Label("N/A")
        self["info_cover"] = Pixmap()
        
        self["tablist"] = self.tablist
        self["streamlist"] = MenuList([])
        
        self["button_red"] = Label(_("play"))
        self["button_green"] = Label(_("skip"))
        self["button_yellow"] = Label(_("love"))
        self["button_blue"] = Label(_("ban"))
        self["infolabel"] = Label("")
        
        self["actions"] = ActionMap(["InfobarChannelSelection","WizardActions", "DirectionActions","MenuActions","ShortcutActions","GlobalActions","HelpActions","NumberActions"], 
            {
             "ok": self.action_ok,
             "back": self.action_exit,
             "red": self.action_startstop,
             "green": self.skipTrack,
             "yellow": self.love,
             "blue": self.banTrack ,
             "historyNext": self.action_nextTab,
             "historyBack": self.action_prevTab,
             
             "menu": self.action_menu,
             }, -1)
        
        self.helpList.append((self["actions"], "WizardActions", [("ok", _("switch to selected Station"))]))
        self.helpList.append((self["actions"], "WizardActions", [("back", _("quit Last.FM"))]))

        self.helpList.append((self["actions"], "MenuActions", [("menu", _("open Configuration"))]))

        self.helpList.append((self["actions"], "ShortcutActions", [("red", _("start/stop streaming"))]))
        self.helpList.append((self["actions"], "ShortcutActions", [("green", _("skip current Track"))]))
        self.helpList.append((self["actions"], "ShortcutActions", [("yellow", _("mark current Track as loved"))]))
        self.helpList.append((self["actions"], "ShortcutActions", [("blue", _("ban Track, never play again"))]))
        self.helpList.append((self["actions"], "InfobarChannelSelection", [("historyNext", _("select next Tab"))]))
        self.helpList.append((self["actions"], "InfobarChannelSelection", [("historyBack", _("select prev Tab"))]))

        self.onLayoutFinish.append(self.initLastFM)
        self.onLayoutFinish.append(self.tabchangedtimerFired)
        self.onLayoutFinish.append(self.setCoverArt)
        
        self.guiupdatetimer = eTimer()
        self.guiupdatetimer.timeout.get().append(self.guiupdatetimerFired)
        self.guiupdatetimer.start(config.plugins.LastFM.metadatarefreshinterval.value*1000)
        
        self.tabchangetimer = eTimer()
        self.tabchangetimer.timeout.get().append(self.tabchangedtimerFired)
        
        self.infolabelcleartimer = eTimer()
        self.infolabelcleartimer.timeout.get().append(self.clearInfoLabel)

        self.screensavertimer = eTimer()
        self.screensavertimer.timeout.get().append(self.startScreensaver)
        self.onShown.append(self.startScreensaverTimer)
        

    def initLastFM(self):
        self.setInfoLabel("loggin into last.fm")
        self.connect(config.plugins.LastFM.username.value,config.plugins.LastFM.password.value)
        
    def onStreamplayerStateChanged(self,reason):
        if reason is self.streamplayer.STATE_PLAYLISTENDS:
            self.loadPlaylist()
        else:
            pass
    def onConnectSuccessful(self,text):
        self.setInfoLabel("login successful")      
    
    def onConnectFailed(self,text):
        self.setInfoLabel("login failed! "+text,timeout=False)

    def onTrackSkiped(self,reason):
        self.setInfoLabel("Track skiped")

    def onTrackLoved(self,reason):
        self.setInfoLabel("Track loved")
    
    def onTrackBanned(self,reason):
        self.setInfoLabel("Track baned")
        
    
    def onCommandFailed(self,reason):
        self.setInfoLabel(reason)

    def onGlobalTagsLoaded(self,tags):
        self.setInfoLabel("Global Tags loaded")
        self.buildMenuList(tags)

    def onTopTracksLoaded(self,tracks):
        self.setInfoLabel("Top Tracks loaded")
        self.buildMenuList(tracks)

    def onRecentTracksLoaded(self,tracks):
        self.setInfoLabel("recent Tracks loaded")
        self.buildMenuList(tracks)
        
    def onRecentBannedTracksLoaded(self,tracks):
        self.setInfoLabel("banned Tracks loaded")
        self.buildMenuList(tracks)

    def onRecentLovedTracksLoaded(self,tracks):
        self.setInfoLabel("loved Tracks loaded")
        self.buildMenuList(tracks)

    def onNeighboursLoaded(self,user):
        self.setInfoLabel("Neighbours loaded")
        self.buildMenuList(user)

    def onFriendsLoaded(self,user):
        self.setInfoLabel("Friends loaded")
        self.buildMenuList(user)
    
    def onStationChanged(self,reason):
        self.setInfoLabel(reason) 
        self.loadPlaylist() 
        
    def onMetadataLoaded(self,metadata):
        self.updateGUI()
        self.guiupdatetimer.start(config.plugins.LastFM.metadatarefreshinterval.value*1000)
    
    def onPlaylistLoaded(self,reason):
        self.streamplayer.setPlaylist(self.playlist)
        self.streamplayer.play()

    def skipTrack(self):
        self.streamplayer.skip()
        self.updateGUI()
        
    def banTrack(self):
        self.ban()
        self.streamplayer.skip()
        self.updateGUI()
        
    def action_TabChanged(self):
        self.tabchangetimer.stop()
        self.tabchangetimer.start(config.plugins.LastFM.timeouttabselect.value*1000)
        
    def guiupdatetimerFired(self):
        self.updateGUI()
        self.guiupdatetimer.start(config.plugins.LastFM.metadatarefreshinterval.value*1000)
        
    def tabchangedtimerFired(self):
        self.tablist.getCurrent()[1][1]()
        self.tabchangetimer.stop()

    def startScreensaverTimer(self):
        self.screensavertimer.start(config.plugins.LastFM.sreensaver.wait.value*1000)

    def resetScreensaverTimer(self):
        self.screensavertimer.stop()
        self.screensavertimer.start(config.plugins.LastFM.sreensaver.wait.value*1000)
        
    def startScreensaver(self):
        if config.plugins.LastFM.sreensaver.use.value:
            self.screensavertimer.stop()
            self.session.openWithCallback(self.updateGUI, LastFMSaveScreen,self)
           
    def action_nextTab(self):
        self.tablist.down()
        self.resetScreensaverTimer()
        
    def action_prevTab(self):
        self.tablist.up()
        self.resetScreensaverTimer()

    def action_menu(self):
        self.session.open(LastFMConfigScreen)
        self.resetScreensaverTimer()

    def action_exit(self):
        self.screensavertimer.stop()
        self.guiupdatetimer.stop()
        self.streamplayer.stop(force=True)
        self.streamplayer.onStateChanged=[]
        
        self.close()

    def action_ok(self):
        x = self["streamlist"].l.getCurrentSelection()
        if x is None:
            pass
        elif len(x) >1:
            if not x[1].startswith('lastfm://'):
                self.customstationtype = x[1]
                text = _("please enter an %s name to listen to"% x[1])
                texts = _("%s name"% x[1])
                self.session.openWithCallback(
                    self.onTextForCustomStationEntered,
                    InputBox,
                    windowTitle = text,
                    title = texts
                    )
            else:
                self.changeStation(x[1])
                self.resetScreensaverTimer()

    def onTextForCustomStationEntered(self,text):
        print "onTextForCustomStationEntered",text,self.customstationtype
        if text is not None:
            if self.customstationtype =="artist":
                self.changeStation(urllib2_qoute("lastfm://artist/%s/similarartists"%text))
            elif self.customstationtype =="groupe":
                self.changeStation(urllib2_qoute("lastfm://group/%s"%text))
            elif self.customstationtype =="tag":
                self.changeStation(urllib2_qoute("lastfm://globaltags/%s"%text))
                        
    def action_startstop(self):
        self.resetScreensaverTimer()
        if self.streamplayer.is_playing:
            self.streamplayer.stop(force=True)
            self.setInfoLabel("stream stopped")
        else:
            self.setInfoLabel("starting stream",timeout=True)
            self.loadPlaylist()
            self.updateGUI() #forcing guiupdate, so we dont wait till guiupdatetimer fired
            self.guiupdatetimer.start(config.plugins.LastFM.metadatarefreshinterval.value*1000)

    def setInfoLabel(self,text,timeout=True):
        self.infolabelcleartimer.stop() 
        self["infolabel"].setText(text)
        if timeout is True:
            self.infolabelcleartimer.start(config.plugins.LastFM.timeoutstatustext.value*1000)
            
    def clearInfoLabel(self):
        self["infolabel"].setText("")
        
    def updateGUI(self):
        if self.streamplayer.is_playing is True:
            self["duration"].setText(self.streamplayer.getRemaining())
        else:
            self["duration"].setText("00:00")
            
        
        if self.streamplayer.is_playing is True:
            self["button_red"].setText(_("stop"))
        else:
            self["button_red"].setText(_("play"))            
        
        if self.streamplayer.is_playing is not True or self.shown is not True:
            return None
            
        if self.streamplayer.is_playing is True:
            self.setTitle("Last.FM: "+self.streamplayer.getMetadata("station"))
        else:
            self.setTitle("Last.FM")

        if self.streamplayer.is_playing is True:
            self["info_artist"].setText(self.streamplayer.getMetadata("creator"))
        else:
            self["info_artist"].setText("N/A")

        if self.streamplayer.is_playing is True:
            self["info_album"].setText(self.streamplayer.getMetadata("album"))
        else:
            self["info_album"].setText("N/A")

        if self.streamplayer.is_playing is True:
            self["info_track"].setText(self.streamplayer.getMetadata("title"))
        else:
            self["info_track"].setText("N/A")
        
        if self.streamplayer.getMetadata("image").startswith("http") and config.plugins.LastFM.showcoverart.value:
            self.imageconverter.convert(self.streamplayer.getMetadata("image"))
        else:
            self.setCoverArt()
        
        if self.streamplayer.is_playing is not True:
            self.setTitle(myname)
            self.setCoverArt()
            self["info_artist"].setText("N/A")
            self["info_album"].setText("N/A")
            self["info_track"].setText("N/A")
        
    def setCoverArt(self,pixmap=None):
        if pixmap is None:
            self["info_cover"].instance.setPixmapFromFile(self.noCoverArtPNG)            
        else:
            self["info_cover"].instance.setPixmap(pixmap.__deref__())
    

    def loadPersonalStations(self):
        tags = []
        x= {}
        x["_display"] = "Personal Recommendations"
        x["stationurl"] = self.getPersonalURL(config.plugins.LastFM.username.value,level=config.plugins.LastFM.recommendedlevel.value)
        tags.append(x)

        x= {}
        x["_display"] = "Neighbours Tracks"
        x["stationurl"] = self.getNeighboursURL(config.plugins.LastFM.username.value)
        tags.append(x)
        
        x= {}
        x["_display"] = "Loved Tracks"
        x["stationurl"] = self.getLovedURL(config.plugins.LastFM.username.value)
        tags.append(x)
        
        x= {}
        x["_display"] = "play Artist Radio ..."
        x["stationurl"] = 'artist'
        tags.append(x)

        x= {}
        x["_display"] = "play Groupe Radio ..."
        x["stationurl"] = 'groupe'
        tags.append(x)
        
        x= {}
        x["_display"] = "play Tag Radio ..."
        x["stationurl"] = 'tag'
        tags.append(x)
        
        
        creator = self.streamplayer.getMetadata("creator")
        if creator != "no creator" and creator != "N/A":
            x= {}
            x["_display"] = "Tracks similar to "+self.streamplayer.getMetadata("creator")
            x["stationurl"] = self.getSimilarArtistsURL(artist=creator)
            tags.append(x)
            
            x= {}
            x["_display"] = "Tracks liked by Fans of "+self.streamplayer.getMetadata("creator")
            x["stationurl"] = self.getArtistsLikedByFans(artist=creator)
            tags.append(x)

            x= {}
            x["_display"] = "Group of "+self.streamplayer.getMetadata("creator")
            x["stationurl"] = self.getArtistGroup(artist=creator)
            tags.append(x)
        
        self.buildMenuList(tags)
        
    def loadGlobalTags(self):
        self.setInfoLabel("loading Global Tags")
        tags = self.getGlobalTags()

    def loadTopTracks(self):
        self.setInfoLabel("loading Top Tacks")
        tracks = self.getTopTracks(config.plugins.LastFM.username.value)

    def loadRecentTracks(self):
        self.setInfoLabel("loading recent Tracks")
        tracks = self.getRecentTracks(config.plugins.LastFM.username.value)

    def loadLovedTracks(self):
        self.setInfoLabel("loading loved Tracks")
        tracks = self.getRecentLovedTracks(config.plugins.LastFM.username.value)

    def loadBannedTracks(self):
        self.setInfoLabel("loading loved Tracks")
        tracks = self.getRecentBannedTracks(config.plugins.LastFM.username.value)
        
    def loadNeighbours(self):
        self.setInfoLabel("loading Neighbours")
        tracks = self.getNeighbours(config.plugins.LastFM.username.value)

    def loadFriends(self):
        self.setInfoLabel("loading Friends")
        tracks = self.getFriends(config.plugins.LastFM.username.value)

    def buildMenuList(self,items):
        menuliste = []
        for i in items:
            menuliste.append((i['_display'],i['stationurl']))
        self["streamlist"].l.setList(menuliste) 
Ejemplo n.º 8
0
class SimpleUPnPBrowser(Screen):
	skin = """
		<screen position="center,center" size="600,475"  title="UPnP Demo-Browser" >
			<widget name="list" position="10,5" size="580,410" scrollbarMode="showOnDemand"/>
		</screen>"""

	def __init__(self, session, enableWrapAround = True):
		Screen.__init__(self, session)
		self.list = MenuList([], enableWrapAround, eListboxPythonMultiContent)
		self.list.l.setFont(0, gFont("Regular", 18))
		self.list.l.setItemHeight(23)

		self["list"] = self.list
		self.browser = UPnPBrowser()

		self["actions"] = ActionMap(["ListboxActions", "OkCancelActions", "ColorActions"],
		{
			"ok" : self.ok,
			"cancel" : self.close,
			"moveUp" : self.moveUp,
			"moveDown" : self.moveDown,
			"pageUp" : self.pageUp,
			"pageDown" : self.pageDown,
		});

		self.browser.onMediaServerDetected.append(self._onMediaServerDetected)
		self.browser.onListReady.append(self._onListReady)
		self.onShow.append( self.__onShow )
		self.onClose.append(self.__onClose)

	def __onShow(self):
		self.browser.browse()

	def __onClose(self):
		self.browser.onMediaServerDetected.remove(self._onMediaServerDetected)
		self.browser.onListReady.remove(self._onListReady)

	def ok(self):
		if self.list.getSelectedIndex() == 0 and self.browser.canAscend():
			print "[SimpleUPnPBrowser].ok can Ascend"
			return self.browser.ascend()

		else:
			item = self.getSelection()[0]
			if item != None:
				if self.browser.canDescend(item):
					self.browser.descend(item)
				else:
					clients = self.browser.controlPoint.getRenderingControlClientList()
					list = [(_("Local"), "local", None, item)] #( Name, UUID, instance )
					for client in clients:
						c = UPnPMediaRenderingControlClient(client)
						devicename = c.getDeviceName()
						list.append( (str(devicename), "remote", c, item) )
					if len(list) > 1:
						self.session.openWithCallback(self.__onRendererSelected, ChoiceBox, title=_("Where do you want to play this?"), list = list)
					else:
						self.__onRendererSelected(list[0])

	def __onRendererSelected(self, selection):
		if selection:
			client = selection[2]
			item = selection[3]
			meta = self.browser.getItemMetadata(item)

			if selection[1] == "local":
				service = eServiceReference(4097,0, meta[Statics.META_URI])
				service.setName(meta[Statics.META_TITLE])
				self.session.nav.playService(service)
			else:
				client.setMediaUri(uri = meta[Statics.META_URI])
				client.play()

	def getSelection(self):
		if self.list.l.getCurrentSelection() is None:
			return None
		return self.list.l.getCurrentSelection()[0]

	def moveUp(self):
		self.list.up()

	def moveDown(self):
		self.list.down()

	def pageUp(self):
		self.list.pageUp()

	def pageDown(self):
		self.list.pageDown()

	def _onMediaServerDetected(self, udn, client):
		#If we cannot ascend anymore we are showing the server list
		#that's the only point where we want to react immediately on server list updates
		if not self.browser.canAscend():
			self._onListReady(self.browser.getList())

	def _onListReady(self, list):
		print "[SimpleUPnPBrowser]._onListReady: got %s items" %(len(list))
		l = []
		if self.browser.canAscend():
			l.append(UPnPEntryComponent( _("[up]") ))
		for item in list:
			l.append(UPnPEntryComponent( self.browser.getItemTitle(item), item, self.browser.getItemType(item) ))

		self.list.l.setList(l)