Esempio n. 1
0
 def __init__(self, text, cutLeft=True, replaceChar='.', replaceCharNum=4):
     self.maxChars = 9999
     self.cutLeft = cutLeft
     self.replaceChar = replaceChar
     self.replaceCharNum = replaceCharNum
     self.testInstance = None
     Label.__init__(self, text)
Esempio n. 2
0
File: Ipkg.py Progetto: TitanNit/tdt
	def __init__(self, session, cmdList = []):
		Screen.__init__(self, session)
		
		self.cmdList = cmdList

		self.sliderPackages = {}
		
		self.slider = Slider(0, len(cmdList))
		self["slider"] = self.slider
		self.activityslider = Slider(0, 100)
		self["activityslider"] = self.activityslider
		self.status = Label(_("Preparing... Please wait"))
		self["status"] = self.status
		self.package = Label()
		self["package"] = self.package
		
		self.packages = 0
		self.error = 0
		
		self.activity = 0
		self.activityTimer = eTimer()
		self.activityTimer.callback.append(self.doActivityTimer)
		#self.activityTimer.start(100, False)
				
		self.ipkg = IpkgComponent()
		self.ipkg.addCallback(self.ipkgCallback)
		
		self.runningCmd = None
		self.runNextCmd()
		
		self["actions"] = ActionMap(["WizardActions"], 
		{
			"ok": self.exit, 
			"back": self.exit
		}, -1)
Esempio n. 3
0
 def __init__(self, session, cmdList = None):
     if not cmdList:
         cmdList = []
     Screen.__init__(self, session)
     self.cmdList = cmdList
     self.sliderPackages = {}
     self.slider = Slider(0, len(cmdList))
     self['slider'] = self.slider
     self.activityslider = Slider(0, 100)
     self['activityslider'] = self.activityslider
     self.status = Label(_('Preparing... Please wait'))
     self['status'] = self.status
     self.package = Label()
     self['package'] = self.package
     self.packages = 0
     self.error = 0
     self.processed_packages = []
     self.activity = 0
     self.activityTimer = eTimer()
     self.activityTimer.callback.append(self.doActivityTimer)
     self.ipkg = IpkgComponent()
     self.ipkg.addCallback(self.ipkgCallback)
     self.runningCmd = None
     self.runNextCmd()
     self['actions'] = ActionMap(['WizardActions'], {'ok': self.exit,
      'back': self.exit}, -1)
     return
Esempio n. 4
0
    def applySkin(self, desktop, parent):
        # testInstance = self.GUI_WIDGET(parent)
        testInstance = self.testInstance
        testInstance.hide()
        testSkinAttributes = []
        if self.skinAttributes:
            for (attrib, value) in self.skinAttributes:
                if attrib == 'size':
                    x, y = value.split(',')
                    x = '2000'
                    new_value = x + ',' + y
                    testSkinAttributes.append((attrib, new_value))
                else:
                    testSkinAttributes.append((attrib, value))
            skin.applyAllAttributes(testInstance, desktop, testSkinAttributes, parent.scale)
        Label.applySkin(self, desktop, parent)
        maxWidth = self.instance.size().width()

        # some random text
        text = 'DSADJASNKDNSJANDJKSANDJKSANDNASJKNDSJKANDJKSANDJKAS'
        text += 'FDSFDSFDSFDSFDSFDSFDSFDSFDSFDSFDSFDSFDSFDSFSDFDSFDS'
        text += 'FDSFDSFDSFDSFDSFDSFDSFDSFDSFDSFDSFDSFDSFDSFSDFDSFDS'
        text += 'FDSFDSFDSFDSFDSFDSFDSFDSFDSFDSFDSFDSFDSFDSFSDFDSFDS'

        testInstance.setText(text)
        actWidth = testInstance.calculateSize().width()
        pixsPerChar = float(actWidth) / float(len(text))
        print actWidth, '/', len(text), '=', pixsPerChar
        print maxWidth
        if pixsPerChar > 0:
            self.maxChars = int(maxWidth / pixsPerChar)
        print self.maxChars
Esempio n. 5
0
	def __init__(self,session):
		Label.__init__(self,text=Channel)
		self.timer=eTimer()
		self.timer_conn = self.timer.timeout.connect(self.updateChanName)
		self.timer.start(500)
		self.oldname=self.text
		self.pipe=MessagePipe()
Esempio n. 6
0
	def __init__(self, text=""):
		self.offset = 0
		self.displayLength = 100

		Label.__init__(self, text)

		self.moveTimer = eTimer()
		self.moveTimer_conn = self.moveTimer.timeout.connect(self.doMove)
	def __init__(self, text=""):
		self.offset = 0
		self.displayLength = 100

		Label.__init__(self, text)

		self.moveTimer = eTimer()
		self.moveTimer.callback.append(self.doMove)
Esempio n. 8
0
 def setText(self, text):
     print len(text), self.maxChars
     if len(text) > self.maxChars:
         cutChars = len(text) - self.maxChars
         if self.cutLeft:
             text = text[cutChars:]
             text = "%s %s" % (self.replaceChar * self.replaceCharNum, text[self.replaceCharNum + 1:])
         else:
             text = text[:self.cutChars]
             text = "%s %s" % (text[:-self.replaceCharNum + 1], self.replaceChar * self.replaceCharNum)
     Label.setText(self, text)
Esempio n. 9
0
	def doMove(self):
		offset = self.offset + 1
		text = self.longText[offset:self.displayLength+offset]
		self.offset = offset

		if not text:
			# it appears we're done displaying the full text, so stop now or waste cpu time forever :D
			self.stopMoving()

		try:
			Label.setText(self, text.encode('utf-8', 'ignore'))
		except Exception:
			self.stopMoving()
	def __init__(self, session, updateurl, version):
		from Components.Slider import Slider

		self.session = session
		Screen.__init__(self, session)
		self.target = updateurl
		self.version = version
		self.file_name = "/tmp/%s" % self.target.split('/')[-1]
		self.fileSize = 5 * 1024
		self.downloadDone = False
		self.container = eConsoleAppContainer()
		self.appClosed_conn = None
		self.stdoutAvail_conn = None

		self['srlog'] = Label()

		self.status = Label(_("Preparing... Please wait"))
		self['status'] = self.status
		self.activityslider = Slider(0, 100)
		self['activityslider'] = self.activityslider
		self.activity = 0
		self.activityTimer = eTimer()
		if isDreamboxOS:
			self.activityTimerConnection = self.activityTimer.timeout.connect(self.doActivityTimer)
		else:
			self.activityTimer.callback.append(self.doActivityTimer)

		self.onLayoutFinish.append(self.__onLayoutFinished)
Esempio n. 11
0
 def __init__(self, session, args = 0):
     self.session = session
     Screen.__init__(self, session)
     self["setupActions"] = ActionMap(["SetupActions", "ColorActions"],
         {
             "cancel": self.cancel,
             "ok": self.keyOk,
         }, -2)
     self.setTitle(_("UserSkin %s") % UserSkinInfo)
     self['skininfo'] = Label("")
     if path.exists(SkinPath + 'skin.config'):
         with open(SkinPath + 'skin.config', "r") as f:
             for line in f:
                 if line.startswith('description='):
                     self['skininfo'].text = line.split('=')[1].replace('"','').replace("'","").strip()
                     break
             f.close()
Esempio n. 12
0
    def __init__(self, session, picPath = None):
        Screen.__init__(self, session)
        print '[sfteambckScreen] __init__\n'
        self.picPath = picPath
        self.Scale = AVSwitch().getFramebufferScale()
        self.PicLoad = ePicLoad()
        self['sftPic'] = Pixmap()
        self['information'] = Label('')
        self['information'].text = _('\n\n\n\nInstructions\n------------------------------\n\n1) Mount HDD in your receiver\n2) En caso necesario monte como HDD pulsando boton azul\n3) Click OK to start the process')
        self['actions'] = ActionMap(['OkCancelActions', 'ColorActions'], {'cancel': self.cancel,
	 'blue': self.mount,
         'green': self.preHaceBackup,
         'red': self.cancel}, -1)
        self['key_red'] = Label(_('Cancel'))
        self['key_green'] = Label(_('OK'))
	self['key_blue'] = Label(_('Mount'))
        self.PicLoad.PictureData.get().append(self.DecodePicture)
        self.onLayoutFinish.append(self.ShowPicture)
Esempio n. 13
0
	def __init__(self, session):
		Screen.__init__(self, session)
		ConfigListScreen.__init__(self, [], session=session)
		self._streamServerControl = streamServerControl
		self._upstreamBitrate = 0
		self._clientCount = streamServerControl.rtspClientCount

		self._key_blue = StaticText("")
		self["key_blue"] = self._key_blue
		self["key_yellow"] = StaticText(_("Presets"))
		self._info = Label("")
		self["info"] = self._info

		self["details_label"] = Label(_("Status Detail"))
		self._details = Label(_("No details available..."))
		self["details"] = self._details
		self._detailsHint = Label("Press PVR in channel selection to change the service in background mode")
		self["details_hint"] = self._detailsHint

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

		self._closeAfterApply = False
		self._presetChoiceBox = None

		self["setupActions"] = ActionMap(["OkCancelActions", "ColorActions"],
		{
			"blue": self.apply,
			"yellow": self._showPresets,
			"cancel": self._applyAndClose,
			"ok" : self._applyAndClose,
		}, -2)

		self.setTitle(_("Streaming Server"))

		streamServerControl.onRtspClientCountChanged.append(self._onRtspClientCountChanged)

		self._streamServerControl.config.streamserver.rtsp.enabled.addNotifier(self._onEnabled, initial_call=False)
		self._streamServerControl.config.streamserver.hls.enabled.addNotifier(self._onEnabled, initial_call=False)
		self._streamServerControl.config.streamserver.gopLength.addNotifier(self._onGopLengthChanged, initial_call=False)
		self._streamServerControl.config.streamserver.bFrames.addNotifier(self._onBframesChanged, initial_call=False)
		self._createSetup()
Esempio n. 14
0
File: plugin.py Progetto: aassww/xta
    def __init__(self, session):
        self.session = session
        path = '/usr/lib/enigma2/python/Plugins/Extensions/iSkin/Skin/Main.xml'
        with open(path, 'r') as f:
            self.skin = f.read()
            f.close()
        mdom = xml.etree.cElementTree.parse(path)
        for x in mdom.getroot():
            if x.tag == 'widget' and x.get('name') == 'cover':
                Size = x.get('size').split(',')
                self.SizeY = int(Size[0])
                self.SizeX = int(Size[1])

        Screen.__init__(self, session)
        self['Key_Red'] = Label(_('Exit'))
        self['Key_Green'] = Label('')
        self['Key_Yellow'] = Label('')
        self['ButtonYellow'] = Pixmap()
        self['ButtonYellow'].hide()
        if os.path.exists('/usr/lib/enigma2/python/Components/Converter/TestConnection.pyo'):
            self['Key_Yellow'].setText(_('Config Connection'))
            self['ButtonYellow'].show()
        self.Region = Label('')
        self['Key_Region'] = self.Region
        self.Key_Blu = Label('')
        self['Key_Blu'] = self.Key_Blu
        self['SkinSelect'] = iMenuList([])
        self.isMoving = False
        self['cover'] = Pixmap()
        self.Loop = eTimer()
        self.Loop.stop()
        self.Loop.callback.append(self.Cover)
        self['setupActions'] = ActionMap(['SkinActionSetup'], {'blue': self.keyBlue,
         'green': self.keyGreen,
         'yellow': self.keyYellow,
         'ok': self.keyOK,
         'up': self.up,
         'down': self.down,
         'red': self.close,
         'cancel': self.close}, -1)
        self.onLayoutFinish.append(self.layoutFinished)
        self.onShown.append(self.SetButtonWeather)
Esempio n. 15
0
	def applySkin(self, desktop, screen):
		if self.skinAttributes is not None:
			attribs = []
			append = attribs.append
			for attrib, value in self.skinAttributes:
				if attrib == "displayLength":
					self.displayLength = int(value)
				else:
					append((attrib, value))
			self.skinAttributes = attribs
		return Label.applySkin(self, desktop, screen)
Esempio n. 16
0
    def __init__(self, groupTimer=None):
        Label.__init__(self)

        self.moving = False

        # TODO: get real values
        self.x = 0.0
        self.y = 0.0

        self.xDest = 0.0
        self.yDest = 0.0

        self.clearPath()

        self.isGroupTimer = groupTimer is not None
        if self.isGroupTimer:
            self.moveTimer = groupTimer
        else:
            self.moveTimer = eTimer()
        self.moveTimer.callback.append(self.doMove)
Esempio n. 17
0
	def __init__(self, session): 
		Screen.__init__(self, session)
                self.session = session
		self.list = []
		ConfigListScreen.__init__(self, self.list)
		
		#refresh devices
		iInputDevices.getInputDevices()
		self.browser_root = "/usr/bin"
		
		self.browser_name = "arora"
		self.conf_file = "/usr/lib/enigma2/python/Plugins/Extensions/WebBrowser/settings.conf"
		self["actions"] = ActionMap(["OkCancelActions", "ShortcutActions", "WizardActions", "ColorActions", "SetupActions", ],
                {	"red": self.keyCancel,
			"green": self.keyGo,
			"cancel": self.keyExit,
                }, -2)
		self.info = Label(_("If you want to quit the Browser,\nPress RED -> EXIT."))
		self["info"] = self.info
		self["key_red"] = StaticText(_("Exit"))
		self["key_green"] = StaticText(_("Start"))

		self.conf_alpha = ""
		self.conf_mouse = ""
		self.conf_keyboard = ""
		self.conf_keymap = ""

		self.usb_mouse = None
		self.usb_keyboard = None
		self.rc_mouse = None
		self.rc_keyboard = None

		self.current_lang_idx = language.getActiveLanguageIndex()

		self.makeConfig()
		#time.sleep(2)
		excute_cmd("echo 1 > /proc/stb/fp/mouse")

		self.lock = False
		self.service = PlayerService(self.session)
		self.service.start(timeout=5)

		self.exit_wait_cond = False
		self.timer_exit_cond = eTimer()
		self.timer_exit_cond.callback.append(self.resetExitCond)

		self.test_cond = True
Esempio n. 18
0
	def __init__(self, session): 
		Screen.__init__(self, session)
		

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

		self.browser_root = "/usr/bin"
		self.browser_name = "arora"

		from Tools.Directories import resolveFilename, SCOPE_PLUGINS
		self.conf_file = resolveFilename(SCOPE_PLUGINS, "Extensions/WebBrowser/settings.conf")
		self["actions"] = ActionMap(["OkCancelActions", "ShortcutActions", "WizardActions", "ColorActions", "SetupActions", ],
                {	"red": self.keyCancel,
			"green": self.keyGo,
			"cancel": self.keyExit,
                }, -2)
		self.info = Label(_("If you want to quit the Browser,\nPress RED -> EXIT."))
		self["info"] = self.info
		self["key_red"] = StaticText(_("Exit"))
		self["key_green"] = StaticText(_("Start"))

		self.conf_alpha = ""
		self.conf_mouse = ""
		self.conf_keyboard = ""
		self.conf_keymap = ""

		self.usb_mouse = None
		self.usb_keyboard = None
		self.rc_mouse = None
		self.rc_keyboard = None

		self.makeConfig()
		#time.sleep(2)

		self.lock = False
		self.vu_service = VuPlayerService(self.session)
		self.vu_service.start(timeout=5)

		self.exit_wait_cond = False
		self.timer_exit_cond = eTimer()
		self.timer_exit_cond.callback.append(self.resetExitCond)

		self.test_cond = True
		self.current_lang_idx = language.getActiveLanguageIndex()
Esempio n. 19
0
  def SetMessage(self, msg):
    if not self.has_key("Statusbar"):
      self["Statusbar"] = Label("")    

    self["Statusbar"].text = str(msg)
Esempio n. 20
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"
Esempio n. 21
0
File: Ipkg.py Progetto: popazerty/12
class Ipkg(Screen):
	def __init__(self, session, cmdList = []):
		Screen.__init__(self, session)
		
		self.cmdList = cmdList

		self.sliderPackages = {}
		
		self.slider = Slider(0, len(cmdList))
		self["slider"] = self.slider
		self.activityslider = Slider(0, 100)
		self["activityslider"] = self.activityslider
		self.status = Label(_("Preparing... Please wait"))
		self["status"] = self.status
		self.package = Label()
		self["package"] = self.package
		
		self.packages = 0
		self.error = 0
		self.processed_packages = []
		
		self.activity = 0
		self.activityTimer = eTimer()
		self.activityTimer_conn = self.activityTimer.timeout.connect(self.doActivityTimer)
		#self.activityTimer.start(100, False)
				
		self.ipkg = IpkgComponent()
		self.ipkg.addCallback(self.ipkgCallback)
		
		self.runningCmd = None
		self.runNextCmd()
		
		self["actions"] = ActionMap(["WizardActions"], 
		{
			"ok": self.exit, 
			"back": self.exit
		}, -1)
		
	def runNextCmd(self):
		if self.runningCmd is None:
			self.runningCmd = 0
		else:
			self.runningCmd += 1
		print len(self.cmdList), self.runningCmd
		if len(self.cmdList) - 1 < self.runningCmd:
			self.activityslider.setValue(0)
			self.slider.setValue(len(self.cmdList))
				
			self.package.setText("")
			self.status.setText(_("Done - Installed, upgraded or removed %d packages with %d errors") % (self.packages, self.error))
			return False
		else:
			cmd = self.cmdList[self.runningCmd]
			self.slider.setValue(self.runningCmd)
			self.ipkg.startCmd(cmd[0], args = cmd[1])
			self.startActivityTimer()
			
	def doActivityTimer(self):
		if not self.ipkg.isRunning():
			self.stopActivityTimer()
		else:
			self.activity += 1
			if self.activity == 100:
				self.activity = 0
			self.activityslider.setValue(self.activity)
		
	def startActivityTimer(self):
		self.activityTimer.start(100, False)
		
	def stopActivityTimer(self):
		self.activityTimer.stop()
		
	def ipkgCallback(self, event, param):
		if event == IpkgComponent.EVENT_DOWNLOAD:
			self.status.setText(_("Downloading"))
		elif event == IpkgComponent.EVENT_UPGRADE:
			if self.sliderPackages.has_key(param):
				self.slider.setValue(self.sliderPackages[param])
			self.package.setText(param)
			self.status.setText(_("Upgrading"))
			if not param in self.processed_packages:
				self.processed_packages.append(param)
				self.packages += 1
		elif event == IpkgComponent.EVENT_INSTALL:
			self.package.setText(param)
			self.status.setText(_("Installing"))
			if not param in self.processed_packages:
				self.processed_packages.append(param)
				self.packages += 1
		elif event == IpkgComponent.EVENT_REMOVE:
			self.package.setText(param)
			self.status.setText(_("Removing"))
			if not param in self.processed_packages:
				self.processed_packages.append(param)
				self.packages += 1
		elif event == IpkgComponent.EVENT_CONFIGURING:
			self.package.setText(param)
			self.status.setText(_("Configuring"))
		elif event == IpkgComponent.EVENT_ERROR:
			self.error += 1
		elif event == IpkgComponent.EVENT_DONE:
			self.runNextCmd()

	def exit(self):
		if not self.ipkg.isRunning():
			self.close()
Esempio n. 22
0
class StreamServerConfig(Screen, ConfigListScreen):
	skin = """
		<screen name="StreamServerConfig" position="center,120" size="920,520" title="Stream Server configuration">
			<ePixmap pixmap="skin_default/buttons/yellow.png" position="10,5" size="200,40" />
			<ePixmap pixmap="skin_default/buttons/blue.png" position="210,5" size="200,40" />
			<widget source="key_yellow" render="Label" position="10,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-2,-2" />
			<widget source="key_blue" render="Label" position="210,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-2,-2" />
			<eLabel position="10,50" size="560,1" backgroundColor="grey" />
			<widget name="config" position="10,55" size="560,450" scrollbarMode="showOnDemand" zPosition="1"/>
			<ePixmap position="580,5" size="330,500" pixmap="skin_default/menu.png" zPosition="-1" scale="stretch"/>
			<!-- details -->
			<widget name="details_label" position="590,20" zPosition="2" size="300,25" font="Regular;20" backgroundColor="background" halign="center" transparent="1" />
			<widget name="details" position="590,50" zPosition="2" size="300,320" font="Regular;18" backgroundColor="background" halign="center" transparent="1" />
			<widget name="details_hint" position="580,390" zPosition="2" size="330,45" font="Regular;17" backgroundColor="background" halign="center" transparent="1" />
			<!-- info -->
			<widget name="info" position="590,450" zPosition="2" size="310,45" font="Regular;17" halign="center" valign="bottom" backgroundColor="background" transparent="1" />
		</screen>"""

	PRESETS = [
		EncoderPreset(_("Very Low"), 800, 64, StreamServerControl.RES_KEY_PAL),
		EncoderPreset(_("Low"), 1200, 96, StreamServerControl.RES_KEY_PAL),
		EncoderPreset(_("Medium"), 2000, 128, StreamServerControl.RES_KEY_720P),
		EncoderPreset(_("High"), 4000, 192, StreamServerControl.RES_KEY_720P),
		EncoderPreset(_("Higher"), 6000, 256, StreamServerControl.RES_KEY_1080P),
		EncoderPreset(_("Best"), 8000, 256, StreamServerControl.RES_KEY_1080P),
		EncoderPreset(_("Maximum"), 10000, 448, StreamServerControl.RES_KEY_1080P),
	]

	def __init__(self, session):
		Screen.__init__(self, session)
		ConfigListScreen.__init__(self, [], session=session)
		self._streamServerControl = streamServerControl
		self._upstreamBitrate = 0
		self._clientCount = streamServerControl.rtspClientCount

		self._key_blue = StaticText("")
		self["key_blue"] = self._key_blue
		self["key_yellow"] = StaticText(_("Presets"))
		self._info = Label("")
		self["info"] = self._info

		self["details_label"] = Label(_("Status Detail"))
		self._details = Label(_("No details available..."))
		self["details"] = self._details
		self._detailsHint = Label("Press PVR in channel selection to change the service in background mode")
		self["details_hint"] = self._detailsHint

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

		self._closeAfterApply = False
		self._presetChoiceBox = None

		self["setupActions"] = ActionMap(["OkCancelActions", "ColorActions"],
		{
			"blue": self.apply,
			"yellow": self._showPresets,
			"cancel": self._applyAndClose,
			"ok" : self._applyAndClose,
		}, -2)

		self.setTitle(_("Streaming Server"))

		streamServerControl.onRtspClientCountChanged.append(self._onRtspClientCountChanged)

		self._streamServerControl.config.streamserver.rtsp.enabled.addNotifier(self._onEnabled, initial_call=False)
		self._streamServerControl.config.streamserver.hls.enabled.addNotifier(self._onEnabled, initial_call=False)
		self._streamServerControl.config.streamserver.gopLength.addNotifier(self._onGopLengthChanged, initial_call=False)
		self._streamServerControl.config.streamserver.bFrames.addNotifier(self._onBframesChanged, initial_call=False)
		self._createSetup()

	def _onBframesChanged(self, element):
		self._createSetup()

	def _onRtspClientCountChanged(self, count, client):
		self._clientCount = count
		self._setInfoText()

	def _onLoginCreated(self, *args):
		self._createSetup()

	def _onClientStreamUrlChanged(self, *args):
		self._setInfoText()

	def apply(self):
		applyConfig(self._streamServerControl)
		if self._closeAfterApply:
			self.close()

	def _applyAndClose(self):
		self._closeAfterApply = True
		self.apply()

	def close(self):
		streamServerControl.onRtspClientCountChanged.remove(self._onRtspClientCountChanged)

		self._streamServerControl.config.streamserver.rtsp.enabled.removeNotifier(self._onEnabled)
		self._streamServerControl.config.streamserver.hls.enabled.removeNotifier(self._onEnabled)
		self._streamServerControl.config.streamserver.gopLength.removeNotifier(self._onGopLengthChanged)
		self._streamServerControl.config.streamserver.bFrames.removeNotifier(self._onBframesChanged)
		self._streamServerControl.config.streamserver.save()

		Screen.close(self)

	def _onEnabled(self, element):
		self.apply()
		self._streamServerControl.config.streamserver.save()
		self._createSetup()

	def _onGopLengthChanged(self, element):
		self._createSetup()

	def _onMediatorEnabled(self, element):
		self._createSetup()

	def _createSetup(self):
		self._setInfoText()

		entries = [ getConfigListEntry(_("RTSP")),
					getConfigListEntry(_("RTSP Server"), self._streamServerControl.config.streamserver.rtsp.enabled),]

		if self._streamServerControl.config.streamserver.rtsp.enabled.value:
			entries.extend([
				getConfigListEntry(_("User"), self._streamServerControl.config.streamserver.rtsp.user),
				getConfigListEntry(_("Password"), self._streamServerControl.config.streamserver.rtsp.password),
			])
			if config.usage.setup_level.index > 0:
				entries.extend([
					#getConfigListEntry(_("RTSP Port"), self._streamServerControl.config.streamserver.rtsp.port),
					getConfigListEntry(_("RTSP Path"), self._streamServerControl.config.streamserver.rtsp.path),
				])

		entries.extend([
			getConfigListEntry(_("HLS")),
			getConfigListEntry(_("HLS Server"), self._streamServerControl.config.streamserver.hls.enabled)
		])
		if self._streamServerControl.config.streamserver.hls.enabled.value:
			entries.extend([
				getConfigListEntry(_("User"), self._streamServerControl.config.streamserver.hls.user),
				getConfigListEntry(_("Password"), self._streamServerControl.config.streamserver.hls.password)
			])
			if config.usage.setup_level.index > 0:
				entries.append(getConfigListEntry(_("Path"), self._streamServerControl.config.streamserver.hls.path))

		if self._streamServerControl.isAnyEnabled():
			entries.extend([
					getConfigListEntry(_("Bitrates")),
					getConfigListEntry(_("Audio Bitrate"),self. _streamServerControl.config.streamserver.audioBitrate),
					getConfigListEntry(_("Video Bitrate"), self._streamServerControl.config.streamserver.videoBitrate),
					getConfigListEntry(_("Basic Encoder Settings")),
					getConfigListEntry(_("Data Source"), self._streamServerControl.config.streamserver.source),
					getConfigListEntry(_("Resolution"), self._streamServerControl.config.streamserver.resolution),
					getConfigListEntry(_("Framerate"), self._streamServerControl.config.streamserver.framerate),
					getConfigListEntry(_("Expert Encoder Settings")),
					getConfigListEntry(_("GOP Length (ms, P-Frames auto calculated)"), self._streamServerControl.config.streamserver.gopLength)
				])

			if self._streamServerControl.config.streamserver.gopLength.value == eStreamServer.GOP_LENGTH_AUTO:
				entries.append( getConfigListEntry(_("Number of P-Frames"), self._streamServerControl.config.streamserver.pFrames) )

			entries.append( getConfigListEntry(_("Number of B-Frames"), self._streamServerControl.config.streamserver.bFrames) )

			if self._streamServerControl.config.streamserver.bFrames.value:
				entries.append( getConfigListEntry(_("Open GOP"), self._streamServerControl.config.streamserver.openGop) )

			if StreamServerControl.FEATURE_SCENE_DETECTION and not self._streamServerControl.config.streamserver.bFrames.value and not self._streamServerControl.config.streamserver.gopLength.value:
				entries.append( getConfigListEntry(_("New GOP On Scene Change"), self._streamServerControl.config.streamserver.gopOnSceneChange) )

			if StreamServerControl.FEATURE_SLICES:
				entries.append( getConfigListEntry(_("Number of slices"), self._streamServerControl.config.streamserver.slices) )

			entries.extend([
					getConfigListEntry(_("Level"), self._streamServerControl.config.streamserver.level),
					getConfigListEntry(_("Profile"), self._streamServerControl.config.streamserver.profile),
				])

		self["config"].list = entries

	def _setInfoText(self):
		detailtext =_("Local client(s):\n    %s") %(self._clientCount)
		self._details.setText(detailtext)

		localstreams = []
		if self._streamServerControl.config.streamserver.rtsp.enabled.value or self._streamServerControl.config.streamserver.hls.enabled.value:
			ifaces = iNetworkInfo.getConfiguredInterfaces()
			for iface in ifaces.itervalues():
				ip = iface.getIpv4()
				if not ip:
					ip = iface.getIpv6()
				if ip:
					if self._streamServerControl.config.streamserver.rtsp.enabled.value:
						localstreams.append("rtsp://%s:%s/%s" %(ip.getAddress(), self._streamServerControl.config.streamserver.rtsp.port.value, self._streamServerControl.config.streamserver.rtsp.path.value))
					if self._streamServerControl.config.streamserver.hls.enabled.value:
						localstreams.append("http://%s:%s/%s.m3u8" %(ip.getAddress(), self._streamServerControl.config.streamserver.hls.port.value, self._streamServerControl.config.streamserver.hls.path.value))
					break

		infotext = ""
		if not localstreams:
			infotext = _("no active streams...")
		else:
			infotext = "\n".join(localstreams)
		self._info.setText(infotext)

	def _showPresets(self):
		presets = []
		for preset in self.PRESETS:
			presets.append((preset.name, preset))
		current = self.PRESETS[0]
		title = _("Video Bitrate:\t%s\nAudio Bitrate:\t%s\nResolution:\t%s") %(current.videoBitrate, current.audioBitrate, current.resolution)
		self._presetChoiceBox = self.session.openWithCallback(self._onPresetSelected, ChoiceBox, title=title, titlebartext=_("Encoder Presets"), list=presets)
		self._presetChoiceBox["list"].onSelectionChanged.append(self._onSelectedPresetChanged)
		self._presetChoiceBox.onLayoutFinish.append(self._onSelectedPresetChanged)

	def _onSelectedPresetChanged(self, *args):
		if not self._presetChoiceBox:
			return
		current = self._presetChoiceBox["list"].getCurrent()
		if not current:
			return
		current = current[0][1]
		text = _("Video Bitrate:\t%s\nAudio Bitrate:\t%s\nResolution:\t%s") %(current.videoBitrate, current.audioBitrate, current.resolution)
		self._presetChoiceBox["text"].setText(text)

	def _onPresetSelected(self, choice):
		self._presetChoiceBox = None
		if choice:
			preset = choice[1]
			self._streamServerControl.config.streamserver.videoBitrate.value = preset.videoBitrate
			self._streamServerControl.config.streamserver.audioBitrate.value = preset.audioBitrate
			if preset.resolution != self._streamServerControl.config.streamserver.resolution.value:
				self._streamServerControl.config.streamserver.resolution.value = preset.resolution
			self._createSetup()
Esempio n. 23
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)
Esempio n. 24
0
class BrowserLauncher(ConfigListScreen, Screen):
	skin=   """
		<screen name="BrowserLauncher" position="center,60" size="415,630" title="Web Browser">
			<ePixmap pixmap="skin_default/buttons/red.png" position="75,0" size="140,40" alphatest="on" />
			<ePixmap pixmap="skin_default/buttons/green.png" position="225,0" size="140,40" alphatest="on" />
			<widget source="key_red" render="Label" position="75,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" transparent="1" />
			<widget source="key_green" render="Label" position="225,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" transparent="1" />
			<widget name="config" position="0,50" size="409,100" scrollbarMode="showOnDemand" />
			<ePixmap pixmap="/usr/lib/enigma2/python/Plugins/Extensions/WebBrowser/icons/%s" position="50,155" size="309,435" alphatest="on" />
			<widget name="info" position="50,588" size="309,50" font="Regular;18" halign="center" foregroundColor="blue" transparent="1" />
		</screen>
		""" % model_rc

	def __init__(self, session): 
		Screen.__init__(self, session)
                self.session = session
		self.list = []
		ConfigListScreen.__init__(self, self.list)
		
		#refresh devices
		iInputDevices.getInputDevices()
		self.browser_root = "/usr/bin"
		
		self.browser_name = "arora"
		self.conf_file = "/usr/lib/enigma2/python/Plugins/Extensions/WebBrowser/settings.conf"
		self["actions"] = ActionMap(["OkCancelActions", "ShortcutActions", "WizardActions", "ColorActions", "SetupActions", ],
                {	"red": self.keyCancel,
			"green": self.keyGo,
			"cancel": self.keyExit,
                }, -2)
		self.info = Label(_("If you want to quit the Browser,\nPress RED -> EXIT."))
		self["info"] = self.info
		self["key_red"] = StaticText(_("Exit"))
		self["key_green"] = StaticText(_("Start"))

		self.conf_alpha = ""
		self.conf_mouse = ""
		self.conf_keyboard = ""
		self.conf_keymap = ""

		self.usb_mouse = None
		self.usb_keyboard = None
		self.rc_mouse = None
		self.rc_keyboard = None

		self.current_lang_idx = language.getActiveLanguageIndex()

		self.makeConfig()
		#time.sleep(2)
		excute_cmd("echo 1 > /proc/stb/fp/mouse")

		self.lock = False
		self.service = PlayerService(self.session)
		self.service.start(timeout=5)

		self.exit_wait_cond = False
		self.timer_exit_cond = eTimer()
		self.timer_exit_cond.callback.append(self.resetExitCond)

		self.test_cond = True

	def keyNone(self):
		None

	def doExit(self):
		change_galpha(set_const=False, set_value=False)
		self.saveConfig()
		self.service.stop()
		excute_cmd("killall -15 %s"%(self.browser_name))
		excute_cmd("echo 60 > /proc/sys/vm/swappiness")
		excute_cmd("echo 0 > /proc/stb/fp/mouse")
		enable_rc_mouse(False) #rc-mouse off
		language.activateLanguageIndex(self.current_lang_idx)
		fbClass.getInstance().unlock()
		#eRCInput.getInstance().unlock()
		self.close()

	def keyExit(self):
		if self.exit_wait_cond:
			self.doExit()
		if is_process_running(self.browser_name) == False:
			self.doExit()

	def keyLeft(self):
		if is_process_running(self.browser_name) == False:
			ConfigListScreen.keyLeft(self)
			global alpha_value
			alpha_value = self.alpha.value
			#self.saveConfig()

	def keyRight(self):
		if is_process_running(self.browser_name) == False:
			ConfigListScreen.keyRight(self)
			alpha_value = self.alpha.value
			#self.saveConfig()

	def keyCancel(self):
		if is_process_running(self.browser_name) == False:
			self.doExit()
		self.exit_wait_cond = True
		self.timer_exit_cond.start(5000)

	# mouse:keyboard:alpha_value
	def saveConfig(self):
		if is_process_running(self.browser_name) == False:
			command = "echo \"%s:%s:%d:%s\" > %s"%(self.mouse.value, self.keyboard.value, int(self.alpha.value), self.langs.value, self.conf_file)
			excute_cmd(command)

	# mouse:keyboard:alpha_value
	def loadConfig(self):
		if os.path.exists(self.conf_file) == False:
			return
		config_list = open(self.conf_file).readline().strip().split(':')
		if len(config_list) == 3:
			self.conf_mouse 	= config_list[0]
			self.conf_keyboard 	= config_list[1]
			self.conf_alpha 	= config_list[2]
		elif len(config_list) == 4:
			self.conf_mouse 	= config_list[0]
			self.conf_keyboard 	= config_list[1]
			self.conf_alpha 	= config_list[2]
			self.conf_keymap 	= config_list[3]
		print "load config : ", config_list

	def resetExitCond(self):
		self.timer_exit_cond.stop()
		self.exit_wait_cond = False

	def makeConfig(self):
		self.loadConfig()
		self.createConfig()


	def createConfig(self):
		self.name_list  = []
		self.mouse_list = None
		self.keyboard_list = None
		
		self.devices = [(x, iInputDevices.getDeviceName(x).replace("dreambox advanced remote control (native)", "Remote Control").replace("dreambox front panel", "Front Panel") + "(" + x  + ")") for x in iInputDevices.getDeviceList()]

		if self.conf_mouse == "":
			self.conf_mouse = "event1"
		self.mouse = ConfigSelection(default = self.conf_mouse, choices = self.devices)
		self.list.append(getConfigListEntry(_('Mouse'), _(self.mouse)))		

		if self.conf_keyboard == "":
			self.conf_keyboard = "event1"
		self.keyboard = ConfigSelection(default = self.conf_keyboard, choices = self.devices)
		self.list.append(getConfigListEntry(_('Keyboard'), _(self.keyboard)))

		if self.conf_alpha == "":
			self.conf_alpha = "255"
		self.alpha = ConfigSlider(default = int(self.conf_alpha), increment = 10, limits = (0, 255))
		self.list.append(getConfigListEntry(_("Alpha Value"), self.alpha))

		if self.conf_keymap == "":
			self.conf_keymap = self.getLanguage()
		self.lang_list = [("en", "English"), ("de", "German")]
		self.langs = ConfigSelection(default = self.conf_keymap, choices = self.lang_list)
		self.list.append(getConfigListEntry(_("Language"), self.langs))

		self["config"].list = self.list
		self["config"].l.setList(self.list)

	def getLanguage(self, lang=language.getLanguage()):
		if self.current_lang_idx == 1:
			return "de"
		return "en"
		

	def startBrowser(self):
		self.timer_start.stop()

		self.lock = True
		excute_cmd("killall -15 %s"%(self.browser_name))
		excute_cmd("echo 0 > /proc/sys/vm/swappiness")

		kbd_cmd = " "
		mouse_cmd = " "
		extra_cmd = " " 
		browser_cmd = "%s/%s -qws" % (self.browser_root, self.browser_name)

		mouse_param = self.mouse.value

		keyboard_param = self.keyboard.value

		keymap_param = ""
		if self.langs.value == "de":
			keymap_param = ":keymap=/usr/share/keymaps/player/de.qmap"

		cmd = "%s%s%s%s" % (extra_cmd, kbd_cmd, mouse_cmd, browser_cmd)
		print "prepared command : [%s]" % cmd

		self.launcher = eConsoleAppContainer()
		self.launcher.appClosed.append(self.callbackLauncherAppClosed)
		self.launcher.dataAvail.append(self.callbackLauncherDataAvail)

		fbClass.getInstance().lock()
		#eRCInput.getInstance().lock()

		global alpha_value
		alpha_value = self.alpha.value
		change_galpha(set_const=True, set_value=True)

		self.launcher.execute(cmd)
		print "started browser..."

	def keyGo(self):
		self.saveConfig()
		self.info.setText("Starting Webbrowser. Please wait...")
		if self.lock == False:
			if self.langs.value == "de":
				language.activateLanguageIndex(1)
			else:
				language.activateLanguageIndex(0)
			self.timer_start = eTimer()
			self.timer_start.callback.append(self.startBrowser)
			self.timer_start.start(10)

	def callbackLauncherDataAvail(self, ret_data):
		print ret_data
		if ret_data.startswith("--done--"):
			self.lock = False
			self.doExit()

	def callbackLauncherAppClosed(self, retval = 1):
		self.lock = False
Esempio n. 25
0
    def __init__(self, session, selectedmovie=None):
        #		print "[SF-Plugin] SF:MovieSelection.init, PWD=%s; selmv=%s" % (config.movielist.last_videodir.value, str(selectedmovie))
        Screen.__init__(self, session)
        HelpableScreen.__init__(self)

        self.tags = []
        if selectedmovie:
            self.selected_tags = config.movielist.last_selected_tags.value
        else:
            self.selected_tags = None
        self.selected_tags_ele = None
        self.toggletype = 0

        self.movemode = False
        self.bouquet_mark_edit = False

        self.delayTimer = eTimer()
        self.delayTimer.callback.append(self.updateHDDData)

        self["waitingtext"] = Label(_("Please wait... Loading list..."))

        # create optional description border and hide immediately
        self["DescriptionBorder"] = Pixmap()
        self["DescriptionBorder"].hide()

        if not fileExists(config.movielist.last_videodir.value):
            config.movielist.last_videodir.value = defaultMoviePath()
            config.movielist.last_videodir.save()
#			print "[SF-Plugin] MovieSelection.MovieSelection: save" + config.movielist.last_videodir.value
        self.current_ref = eServiceReference(
            "2:0:1:0:0:0:0:0:0:0:" + config.movielist.last_videodir.value)

        self["list"] = MovieList(
            None, config.movielist.sflisttype.value,
            config.movielist.sfmoviesort.value, config.movielist.sftimes.value,
            config.movielist.sftitle_episode_separator.value, self)

        self.list = self["list"]
        self.selectedmovie = selectedmovie

        # Need list for init
        SelectionEventInfo.__init__(self)

        self["key_red"] = Button(_("All"))
        self["key_green"] = Button("")
        self["key_yellow"] = Button("")
        self["key_blue"] = Button("")

        self["freeDiskSpace"] = self.diskinfo = DiskInfo(
            config.movielist.last_videodir.value, DiskInfo.FREE, update=False)

        if config.usage.setup_level.index >= 2:  # expert+
            self["InfobarActions"] = HelpableActionMap(
                self, "InfobarActions", {
                    "showMovies":
                    (self.doPathSelect, _("select the movie path")),
                })

        self["MovieSelectionActions"] = HelpableActionMap(
            self, "MovieSelectionActions", {
                "contextMenu": (self.doContext, _("menu")),
                "showEventInfo":
                (self.showEventInformation, _("show event details")),
            })

        self["ColorActions"] = HelpableActionMap(
            self, "ColorActions", {
                "red": (self.showAll, _("show all")),
                "green": (self.showTagsFirst, _("show first selected tag")),
                "yellow": (self.showTagsSecond, _("show second selected tag")),
                "blue": (self.showTagsSelect, _("show tag menu")),
            })

        self["OkCancelActions"] = HelpableActionMap(
            self, "OkCancelActions", {
                "cancel": (self.abort, _("exit movielist")),
                "ok": (self.movieSelected, _("select movie")),
            })

        self["NumberActions"] = HelpableActionMap(
            self, "SetupActions", {
                "0":
                (self.toggleSort, _x("Toggle date / alphabetic sort mode")),
                "deleteBackward":
                (self.moveToIndexStrt, _x("Jump to listbegin")),
                "deleteForward": (self.moveToIndexEnd, _x("Jump to listend")),
                "5":
                (self.toggleMinimal, _x("Toggle style minimal / compact")),
                "8":
                (self.toggleTags, _x("Toggle description / tags display")),
            })

        self.onShown.append(self.go)
        self.onLayoutFinish.append(self.saveListsize)
        self.inited = False
Esempio n. 26
0
	def __init__(self, session, parent):
		Screen.__init__(self, session)
		self["text1"] =  Label("SHOUTcast")
		self["text2"] = Label("")
Esempio n. 27
0
	def __init__(self, session):
		self.session = session
		Screen.__init__(self, session)
		self.oldtitle = None
		self.currentcoverfile = 0
		self.currentGoogle = None
		self.nextGoogle = None
		self.currPlay = None
		self.CurrentService = self.session.nav.getCurrentlyPlayingServiceReference()
		self.session.nav.stopService()
		self.session.nav.event.append(self.__event)
		self["cover"] = Cover()
		self["key_red"] = StaticText(_("Record"))
		self["key_green"] = StaticText(_("Genres"))
		self["key_yellow"] = StaticText(_("Stations"))
		self["key_blue"] = StaticText(_("Favorites"))
		self.mode = self.FAVORITELIST
		self["list"] = SHOUTcastList()
		self["list"].connectSelChanged(self.onSelectionChanged)
		self["statustext"] = Label(_("Getting SHOUTcast genre list..."))
		self["actions"] = ActionMap(["WizardActions", "DirectionActions", "ColorActions", "EPGSelectActions"],
		{
			"ok": self.ok_pressed,
			"back": self.close,
			"menu": self.menu_pressed,
			"red": self.red_pressed,
			"green": self.green_pressed,
			"yellow": self.yellow_pressed,
			"blue": self.blue_pressed,
			
		}, -1)
		self.stationList = []
		self.stationListIndex = 0
		self.genreList = []
		self.genreListIndex = 0
		self.favoriteList = []
		self.favoriteListIndex = 0

		self.favoriteConfig = Config()
		if os.path.exists(self.FAVORITE_FILE):
			self.favoriteConfig.loadFromFile(self.FAVORITE_FILE)
		elif os.path.exists(self.FAVORITE_FILE_OLD):
			self.favoriteConfig.loadFromFile(self.FAVORITE_FILE_OLD)
		else:
			self.favoriteConfig.loadFromFile(self.FAVORITE_FILE_DEFAULT)
		self.favoriteConfig.entriescount =  ConfigInteger(0)
		self.favoriteConfig.Entries = ConfigSubList()
		self.initFavouriteConfig()
		self.stationListXML = ""
		self["titel"] = Label()
		self["station"] = Label()
		self["headertext"] = Label()
		self["console"] = Label()
		self.headerTextString = ""
		self.stationListHeader = ""
		self.tunein = ""
		self.searchSHOUTcastString = ""
		self.currentStreamingURL = ""
		self.currentStreamingStation = ""
		self.stationListURL = ""
		self.onClose.append(self.__onClose)
		self.onLayoutFinish.append(self.getFavoriteList)

		self.reloadStationListTimer = eTimer()
		self.reloadStationListTimer.timeout.get().append(self.reloadStationListTimerTimeout)
		self.reloadStationListTimerVar = int(config.plugins.shoutcast.reloadstationlist.value)

		self.visible = True

		global containerStreamripper
		if containerStreamripper is None:
			containerStreamripper = eConsoleAppContainer()

		containerStreamripper.dataAvail.append(self.streamripperDataAvail)
		containerStreamripper.appClosed.append(self.streamripperClosed)

		if containerStreamripper.running():
			self["key_red"].setText(_("Stop record"))
			# just to hear to recording music when starting the plugin...
			self.currentStreamingStation = _("Recording stream station")
			self.playServiceStream("http://localhost:9191")
Esempio n. 28
0
    def __init__(self,
                 session,
                 service,
                 zapFunc=None,
                 eventid=None,
                 bouquetChangeCB=None,
                 serviceChangeCB=None):
        Screen.__init__(self, session)
        self.bouquetChangeCB = bouquetChangeCB
        self.serviceChangeCB = serviceChangeCB
        self.ask_time = -1  #now
        self["key_red"] = Button("")
        self.closeRecursive = False
        self.saved_title = None
        self["Service"] = ServiceEvent()
        self["Event"] = Event()
        self.session = session
        if isinstance(service, str) and eventid != None:
            self.type = EPG_TYPE_SIMILAR
            self["key_yellow"] = Button()
            self["key_blue"] = Button()
            self["key_red"] = Button()
            self.currentService = service
            self.eventid = eventid
            self.zapFunc = None
        elif isinstance(service, eServiceReference) or isinstance(
                service, str):
            self.type = EPG_TYPE_SINGLE
            self["key_yellow"] = Button()
            self["key_blue"] = Button(_("Select Channel"))
            self.currentService = ServiceReference(service)
            self.zapFunc = zapFunc
            self.sort_type = 0
            self.setSortDescription()
        else:
            self.skinName = "EPGSelectionMulti"
            self.type = EPG_TYPE_MULTI
            self["key_yellow"] = Button(
                pgettext("button label, 'previous screen'", "Prev"))
            self["key_blue"] = Button(
                pgettext("button label, 'next screen'", "Next"))
            self["now_button"] = Pixmap()
            self["next_button"] = Pixmap()
            self["more_button"] = Pixmap()
            self["now_button_sel"] = Pixmap()
            self["next_button_sel"] = Pixmap()
            self["more_button_sel"] = Pixmap()
            self["now_text"] = Label()
            self["next_text"] = Label()
            self["more_text"] = Label()
            self["date"] = Label()
            self.services = service
            self.zapFunc = zapFunc
        self["key_green"] = Button(_("Add timer"))
        self.key_green_choice = self.ADD_TIMER
        self.key_red_choice = self.EMPTY
        self["list"] = EPGList(type=self.type,
                               selChangedCB=self.onSelectionChanged,
                               timer=session.nav.RecordTimer)

        self["actions"] = ActionMap(
            ["EPGSelectActions", "OkCancelActions"],
            {
                "cancel": self.closeScreen,
                "ok": self.eventSelected,
                "timerAdd": self.timerAdd,
                "yellow": self.yellowButtonPressed,
                "blue": self.blueButtonPressed,
                "info": self.infoKeyPressed,
                "red": self.zapTo,
                "menu": self.furtherOptions,
                "nextBouquet": self.nextBouquet,  # just used in multi epg yet
                "prevBouquet": self.prevBouquet,  # just used in multi epg yet
                "nextService": self.nextService,  # just used in single epg yet
                "prevService": self.prevService,  # just used in single epg yet
                "preview": self.eventPreview,
            })
        self["actions"].csel = self
        self.onLayoutFinish.append(self.onCreate)
Esempio n. 29
0
    def __init__(self, session, args=0):
        print("[MakeBouquet][__init__] Starting...")
        print("[MakeBouquet][__init__] args", args)
        self.session = session
        Screen.__init__(self, session)
        Screen.setTitle(self, _("MakeBouquet"))
        self.skinName = ["TerrestrialScan"]

        self.path = "/etc/enigma2"
        self.services_dict = {}
        self.tmp_services_dict = {}
        self.namespace_dict = {
        }  # to store namespace when sub network is enabled
        self.logical_channel_number_dict = {}
        self.ignore_visible_service_flag = False  # make this a user override later if found necessary
        self.VIDEO_ALLOWED_TYPES = [1, 4, 5, 17, 22, 24, 25, 27, 135]
        self.AUDIO_ALLOWED_TYPES = [2, 10]
        self.BOUQUET_PREFIX = "userbouquet.TerrestrialScan."
        self.bouquetsIndexFilename = "bouquets.tv"
        self.bouquetFilename = self.BOUQUET_PREFIX + "tv"
        self.bouquetName = _('Terrestrial')
        self.namespace_complete_terrestrial = not (
            config.usage.subnetwork_terrestrial.value if hasattr(
                config.usage, "subnetwork_terrestrial") else True
        )  # config.usage.subnetwork not available in all images

        self.terrestrialXmlFilename = "terrestrial.xml"

        self.frontend = None
        self.rawchannel = None

        self["background"] = Pixmap()
        self["action"] = Label(_("Starting scanner"))
        self["status"] = Label("")
        self["progress"] = ProgressBar()
        self["progress_text"] = Progress()
        self["tuner_text"] = Label("")
        self["Frontend"] = FrontendStatus(
            frontend_source=lambda: self.frontend, update_interval=100)

        self["actions"] = ActionMap(["SetupActions"], {
            "cancel": self.keyCancel,
        }, -2)

        self.selectedNIM = -1
        self.transponders_unique = {}
        self.FTA_only = False
        self.makebouquet = True
        self.makexmlfile = False
        self.lcndescriptor = 0x83
        self.channel_list_id = 0
        if args:
            if "feid" in args:
                self.selectedNIM = args["feid"]
            if "transponders_unique" in args:
                self.transponders_unique = args["transponders_unique"]
            if "FTA_only" in args:
                self.FTA_only = args["FTA_only"]
            if "makebouquet" in args:
                self.makebouquet = args["makebouquet"]
            if "makexmlfile" in args:
                self.makexmlfile = args["makexmlfile"]
            if "lcndescriptor" in args:
                self.lcndescriptor = args["lcndescriptor"]
            if "channel_list_id" in args:
                self.channel_list_id = args["channel_list_id"]

        self.tsidOnidKeys = list(self.transponders_unique.keys())
        self.index = 0
        self.lockTimeout = 50  # 100ms for tick - 5 sec

        self.onClose.append(self.__onClose)
        self.onFirstExecBegin.append(self.firstExec)
Esempio n. 30
0
    def __init__(self, session, parent):
        Screen.__init__(self, session)
        HelpableScreen.__init__(self)
        self.parentMenu = parent
        self.menuList = []
        self["menu"] = List(self.menuList)
        self["menu"].enableWrapAround = True
        self["menu"].onSelectionChanged.append(self.selectionChanged)
        self.showNumericHelp = False
        self["green"] = Label()
        self["yellow"] = Label()
        self["blue"] = Label()
        self.sort_mode = False
        self.selected_entry = None
        self.sub_menu_sort = None
        self.createMenuList()
        ProtectedScreen.__init__(self)
        # for the skin: first try a menu_<menuID>, then Menu
        self.skinName = []
        if self.menuID is not None:
            if config.usage.menutype.value == "horzanim" and findSkinScreen(
                    "Animmain"):
                self.skinName.append("Animmain")
            elif config.usage.menutype.value == "horzicon" and findSkinScreen(
                    "Iconmain"):
                self.skinName.append("Iconmain")
            else:
                self.skinName.append("menu_" + self.menuID)
        self.skinName.append("Menu")

        if config.usage.menu_sort_mode.value == "user":

            self["MoveActions"] = ActionMap(
                ["WizardActions"], {
                    "left": self.keyLeft,
                    "right": self.keyRight,
                    "up": self.keyUp,
                    "down": self.keyDown,
                }, -1)
            self["EditActions"] = ActionMap(
                ["ColorActions"], {
                    "green": self.keyGreen,
                    "yellow": self.keyYellow,
                    "blue": self.keyBlue,
                })

        self["menuActions"] = HelpableNumberActionMap(
            self, ["OkCancelActions", "NumberActions", "MenuActions"], {
                "ok": (self.okbuttonClick, _("Select the current menu item")),
                "cancel": (self.closeNonRecursive, _("Exit menu")),
                "close": (self.closeRecursive, _("Exit all menus")),
                "menu": (self.closeRecursive, _("Exit all menus")),
                "1": (self.keyNumberGlobal, _("Direct menu item selection")),
                "2": (self.keyNumberGlobal, _("Direct menu item selection")),
                "3": (self.keyNumberGlobal, _("Direct menu item selection")),
                "4": (self.keyNumberGlobal, _("Direct menu item selection")),
                "5": (self.keyNumberGlobal, _("Direct menu item selection")),
                "6": (self.keyNumberGlobal, _("Direct menu item selection")),
                "7": (self.keyNumberGlobal, _("Direct menu item selection")),
                "8": (self.keyNumberGlobal, _("Direct menu item selection")),
                "9": (self.keyNumberGlobal, _("Direct menu item selection")),
                "0": (self.keyNumberGlobal, _("Direct menu item selection"))
            },
            prio=0,
            description=_("Common Menu Actions"))
        title = parent.get("title", "").encode("UTF-8") if PY2 else parent.get(
            "title", "") or None
        title = title and _(title)
        if title is None:
            title = _(parent.get("text", "").encode(
                "UTF-8", "ignore")) if PY2 else _(parent.get("text", ""))
        else:
            t_history.reset()
        self["title"] = StaticText(title)
        self.setTitle(title)
        self.menu_title = title
        self["thistory"] = StaticText(t_history.thistory)
        history_len = len(t_history.thistory)
        self["title0"] = StaticText("")
        self["title1"] = StaticText("")
        self["title2"] = StaticText("")
        if history_len < 13:
            self["title0"] = StaticText(title)
        elif history_len < 21:
            self["title0"] = StaticText("")
            self["title1"] = StaticText(title)
        else:
            self["title0"] = StaticText("")
            self["title1"] = StaticText("")
            self["title2"] = StaticText(title)
        if t_history.thistory == "":
            t_history.thistory = str(title) + " > "
        else:
            t_history.thistory = t_history.thistory + str(title) + " > "
        if config.usage.menutype.value == "horzanim" and findSkinScreen(
                "Animmain"):
            self["label1"] = StaticText()
            self["label2"] = StaticText()
            self["label3"] = StaticText()
            self["label4"] = StaticText()
            self["label5"] = StaticText()
            self.onShown.append(self.openTestA)
        elif config.usage.menutype.value == "horzicon" and findSkinScreen(
                "Iconmain"):
            self["label1"] = StaticText()
            self["label2"] = StaticText()
            self["label3"] = StaticText()
            self["label4"] = StaticText()
            self["label5"] = StaticText()
            self["label6"] = StaticText()
            self["label1s"] = StaticText()
            self["label2s"] = StaticText()
            self["label3s"] = StaticText()
            self["label4s"] = StaticText()
            self["label5s"] = StaticText()
            self["label6s"] = StaticText()
            self["pointer"] = Pixmap()
            self["pixmap1"] = Pixmap()
            self["pixmap2"] = Pixmap()
            self["pixmap3"] = Pixmap()
            self["pixmap4"] = Pixmap()
            self["pixmap5"] = Pixmap()
            self["pixmap6"] = Pixmap()
            self.onShown.append(self.openTestB)
        self.number = 0
        self.nextNumberTimer = eTimer()
        self.nextNumberTimer.callback.append(self.okbuttonClick)
        if len(self.menuList) == 1:
            self.onExecBegin.append(self.__onExecBegin)
        self.onLayoutFinish.append(self.layoutFinished)
Esempio n. 31
0
	def __init__(self, session, type = 0, needupdate = True, menu_path="", skin_name=None):
		Screen.__init__(self, session)
		self.menu_path = menu_path
		self.type = type
		self.needupdate = needupdate
		self.skinName = ["PluginDownloadBrowser"]
		if isinstance(skin_name, str):
			self.skinName.insert(0,skin_name)

		self["menu_path_compressed"] = StaticText("")
		if self.type == self.DOWNLOAD:
			config.misc.pluginbrowser.po.value = True
			screentitle = _("Install plugins")
			if config.usage.show_menupath.value == 'large':
				self.menu_path += screentitle
				title = self.menu_path
				self["menu_path_compressed"].setText("")
			elif config.usage.show_menupath.value == 'small':
				title = screentitle
				self["menu_path_compressed"].setText(self.menu_path + " >" if not self.menu_path.endswith(' / ') else self.menu_path[:-3] + " >" or "")
			else:
				title = screentitle
				self["menu_path_compressed"].setText("")
		elif self.type == self.REMOVE:
			config.misc.pluginbrowser.po.value = False
			screentitle = _("Remove plugins")
			if config.usage.show_menupath.value == 'large':
				self.menu_path += screentitle
				title = self.menu_path
				self["menu_path_compressed"].setText("")
			elif config.usage.show_menupath.value == 'small':
				title = screentitle
				self["menu_path_compressed"].setText(self.menu_path + " >" if not self.menu_path.endswith(' / ') else self.menu_path[:-3] + " >" or "")
			else:
				title = screentitle
				self["menu_path_compressed"].setText("")
		self.setTitle(title)
		self.createPluginFilter()
		self.LanguageList = language.getLanguageListSelection()
		self.container = eConsoleAppContainer()
		self.container.appClosed.append(self.runFinished)
		self.container.dataAvail.append(self.dataAvail)
		self.onLayoutFinish.append(self.startRun)

		self.list = []
		self["list"] = PluginList(self.list)
		self.pluginlist = []
		self.expanded = []
		self.installedplugins = []
		self.plugins_changed = False
		self.reload_settings = False
		self.check_settings = False
		self.check_bootlogo = False
		self.install_settings_name = ''
		self.remove_settings_name = ''
		self.onChangedEntry = []
		self["list"].onSelectionChanged.append(self.selectionChanged)

		if self.type == self.DOWNLOAD:
			self["text"] = Label(_("Downloading plugin information. Please wait..."))
		elif self.type == self.REMOVE:
			self["text"] = Label(_("Getting plugin information. Please wait..."))

		self.run = 0
		self.remainingdata = ""
		self["actions"] = ActionMap(["WizardActions"],
		{
			"ok": self.go,
			"back": self.requestClose,
		})
		if os.path.isfile('/usr/bin/opkg'):
			self.ipkg = '/usr/bin/opkg'
			self.ipkg_install = self.ipkg + ' install'
			self.ipkg_remove =  self.ipkg + ' remove --autoremove'
		else:
			self.ipkg = 'ipkg'
			self.ipkg_install = 'ipkg install -force-defaults'
			self.ipkg_remove =  self.ipkg + ' remove'
Esempio n. 32
0
    def populate(self):
        if isVTISkin:
            self['EnigmaVersion'] = StaticText(
                _('Version') + ': ' + about.getEnigmaVersionString())
            self['ImageVersion'] = StaticText(
                _('Image') + ': ' + about.getImageVersionString())
            self['TunerHeader'] = StaticText(_('Detected NIMs:'))
            fp_version = getFPVersion()
            if fp_version is None:
                fp_version = ''
            else:
                fp_version = _('Frontprocessor version: %d') % fp_version
            self['FPVersion'] = StaticText(fp_version)
            nims = nimmanager.nimList()
            self.tuner_list = []
            if len(nims) <= 4:
                for count in (0, 1, 2, 3, 4, 5, 6, 7):
                    if count < len(nims):
                        self['Tuner' + str(count)] = StaticText(nims[count])
                        self.tuner_list.append(nims[count] + '\n')
                    else:
                        self['Tuner' + str(count)] = StaticText('')

            else:
                desc_list = []
                count = 0
                cur_idx = -1
                while count < len(nims):
                    data = nims[count].split(':')
                    idx = data[0].strip('Tuner').strip()
                    desc = data[1].strip()
                    if desc_list and desc_list[cur_idx]['desc'] == desc:
                        desc_list[cur_idx]['end'] = idx
                    else:
                        desc_list.append({
                            'desc': desc,
                            'start': idx,
                            'end': idx
                        })
                        cur_idx += 1
                    count += 1

                for count in (0, 1, 2, 3, 4, 5, 6, 7):
                    if count < len(desc_list):
                        if desc_list[count]['start'] == desc_list[count][
                                'end']:
                            text = 'Tuner %s: %s' % (desc_list[count]['start'],
                                                     desc_list[count]['desc'])
                        else:
                            text = 'Tuner %s-%s: %s' % (
                                desc_list[count]['start'],
                                desc_list[count]['end'],
                                desc_list[count]['desc'])
                    else:
                        text = ''
                    self['Tuner' + str(count)] = StaticText(text)
                    if text != '':
                        self.tuner_list.append(text + '\n')

            self['HDDHeader'] = StaticText(_('Detected HDD:'))
            hddlist = harddiskmanager.HDDList()
            hdd = hddlist and hddlist[0][1] or None
            if hdd is not None and hdd.model() != '':
                self['hddA'] = StaticText(
                    _('%s\n(%s, %d MB free)') %
                    (hdd.model(), hdd.capacity(), hdd.free()))
            else:
                self['hddA'] = StaticText(_('none'))
            self.enigma2_version = _(
                'Version') + ': ' + about.getEnigmaVersionString()
            self.image_version = _(
                'EGAMI ') + ': ' + about.getImageVersionString()
            cpu_info = parseLines('/proc/cpuinfo')
            cpu_name = 'N/A'
            for line in cpu_info:
                if line.find('model') != -1:
                    cpu_name = line.split(':')
                    if len(cpu_name) >= 2:
                        cpu_name = cpu_name[1].strip()
                    break

            self.cpu = _('CPU') + ': ' + cpu_name
            self.chipset = _('Chipset') + ': ' + parseFile(
                '/proc/stb/info/chipset')
            self.tuner_header = _('Detected NIMs:')
            self.hdd_header = _('Detected HDD:')
            self.hdd_list = []
            if len(hddlist):
                for hddX in hddlist:
                    hdd = hddX[1]
                    if hdd.model() != '':
                        self.hdd_list.append(
                            hdd.model() + '\n   %.2f GB - %.2f GB' %
                            (hdd.diskSize() / 1000.0, hdd.free() / 1000.0) +
                            ' ' + _('free') + '\n\n')

            ifaces = iNetwork.getConfiguredAdapters()
            iface_list = []
            for iface in ifaces:
                iface_list.append(
                    _('Interface') + ' : ' + iNetwork.getAdapterName(iface) +
                    ' (' + iNetwork.getFriendlyAdapterName(iface) + ')\n')
                iface_list.append(
                    _('IP') + ' : ' +
                    parse_ipv4(iNetwork.getAdapterAttribute(iface, 'ip')) +
                    '\n')
                iface_list.append(
                    _('Netmask') + ' : ' + parse_ipv4(
                        iNetwork.getAdapterAttribute(iface, 'netmask')) + '\n')
                iface_list.append(
                    _('Gateway') + ' : ' + parse_ipv4(
                        iNetwork.getAdapterAttribute(iface, 'gateway')) + '\n')
                if iNetwork.getAdapterAttribute(iface, 'dhcp'):
                    iface_list.append(_('DHCP') + ' : ' + _('Yes') + '\n')
                else:
                    iface_list.append(_('DHCP') + ' : ' + _('No') + '\n')
                iface_list.append(
                    _('MAC') + ' : ' +
                    iNetwork.getAdapterAttribute(iface, 'mac') + '\n')
                iface_list.append('\n')

            my_txt = self.enigma2_version + '\n'
            my_txt += self.image_version + '\n'
            my_txt += '\n'
            my_txt += self.cpu + '\n'
            my_txt += self.chipset + '\n'
            my_txt += '\n'
            my_txt += self.tuner_header + '\n'
            for x in self.tuner_list:
                my_txt += '   ' + x

            my_txt += '\n'
            my_txt += _('Network') + ':\n'
            for x in iface_list:
                my_txt += '   ' + x

            my_txt += self.hdd_header + '\n'
            for x in self.hdd_list:
                my_txt += '   ' + x

            my_txt += '\n'
            self['FullAbout'] = ScrollLabel(my_txt)
        else:
            EGAMIVersion = _('EGAMI %s') % about.getImageVersionString()
            self['lab1'] = Label(EGAMIVersion)
            model = None
            AboutText = getAboutText()[0]
            self['AboutScrollLabel'] = ScrollLabel(AboutText)
Esempio n. 33
0
 def __init__(self, session, parent):
     Screen.__init__(self, session)
     self["text1"] = Label("Playing")
     self["text2"] = Label("")
     self["text3"] = Label("")
     self["text4"] = Label("")
Esempio n. 34
0
	def __init__(self, session, infobar):
		Screen.__init__(self, session)
		self.infobar = infobar or self.session.infobar

		self.wait = eTimer()
		self.wait.timeout.get().append(self.resyncSubtitles)

		self.resume = eTimer()
		self.resume.timeout.get().append(self.resyncSubtitlesResume)

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

		sub = self.infobar.selected_subtitle
		if sub[0] == 0:  # dvb
			menu = [
				getConfigMenuItem("config.subtitles.dvb_subtitles_yellow"),
				getConfigMenuItem("config.subtitles.dvb_subtitles_centered"),
				getConfigMenuItem("config.subtitles.dvb_subtitles_backtrans"),
				getConfigMenuItem("config.subtitles.dvb_subtitles_original_position"),
				getConfigMenuItem("config.subtitles.subtitle_position"),
				getConfigMenuItem("config.subtitles.subtitle_bad_timing_delay"),
				getConfigMenuItem("config.subtitles.subtitle_noPTSrecordingdelay"),
			]
		elif sub[0] == 1: # teletext
			menu = [
				getConfigMenuItem("config.subtitles.ttx_subtitle_colors"),
				getConfigMenuItem("config.subtitles.ttx_subtitle_original_position"),
				getConfigMenuItem("config.subtitles.subtitle_fontsize"),
				getConfigMenuItem("config.subtitles.subtitle_position"),
				getConfigMenuItem("config.subtitles.subtitle_rewrap"),
				getConfigMenuItem("config.subtitles.subtitle_borderwidth"),
				getConfigMenuItem("config.subtitles.subtitle_alignment"),
				getConfigMenuItem("config.subtitles.subtitle_bad_timing_delay"),
				getConfigMenuItem("config.subtitles.subtitle_noPTSrecordingdelay"),
			]
		else: 		# pango
			menu = [
				getConfigMenuItem("config.subtitles.pango_subtitles_delay"),
				getConfigMenuItem("config.subtitles.pango_subtitle_colors"),
				getConfigMenuItem("config.subtitles.pango_subtitle_fontswitch"),
				getConfigMenuItem("config.subtitles.colourise_dialogs"),
				getConfigMenuItem("config.subtitles.subtitle_fontsize"),
				getConfigMenuItem("config.subtitles.subtitle_position"),
				getConfigMenuItem("config.subtitles.subtitle_alignment"),
				getConfigMenuItem("config.subtitles.subtitle_rewrap"),
				getConfigMenuItem("config.subtitles.pango_subtitle_removehi"),
				getConfigMenuItem("config.subtitles.subtitle_borderwidth"),
				getConfigMenuItem("config.subtitles.pango_subtitles_fps"),
			]
			self["videofps"].setText(_("Video: %s fps") % (self.getFps().rstrip(".000")))

		ConfigListScreen.__init__(self, menu, self.session, on_change = self.changedEntry)

		self["actions"] = NumberActionMap(["SetupActions"],
		{
			"cancel": self.cancel,
			"ok": self.ok,
			"1": self.keyNumber,
			"3": self.keyNumber,
			"4": self.keyNumber,
			"6": self.keyNumber,
			"7": self.keyNumber,
			"9": self.keyNumber,
			"0": self.keyNumber,
		},-2)

		self.onLayoutFinish.append(self.layoutFinished)
Esempio n. 35
0
	def setText(self, text):
		text = (self.displayLength * ' ') + text
		self.longText = text
		self.offset = 0
		Label.setText(self, text[:self.displayLength].encode('utf-8', 'ignore'))
Esempio n. 36
0
	def __init__(self, session, dvd_device = None, dvd_filelist = [ ], args = None):
		Screen.__init__(self, session)
		InfoBarBase.__init__(self)
		InfoBarNotifications.__init__(self)
		InfoBarCueSheetSupport.__init__(self, actionmap = "MediaPlayerCueSheetActions")
		InfoBarShowHide.__init__(self)
		InfoBarAudioSelection.__init__(self)
		InfoBarSubtitleSupport.__init__(self)
		HelpableScreen.__init__(self)
		self.save_infobar_seek_config()
		self.change_infobar_seek_config()
		InfoBarSeek.__init__(self)
		InfoBarPVRState.__init__(self)

		self.oldService = self.session.nav.getCurrentlyPlayingServiceOrGroup()
		self.session.nav.stopService()
		self["audioLabel"] = Label("n/a")
		self["subtitleLabel"] = Label("")
		self["angleLabel"] = Label("")
		self["chapterLabel"] = Label("")
		self["anglePix"] = Pixmap()
		self["anglePix"].hide()
		self.last_audioTuple = None
		self.last_subtitleTuple = None
		self.last_angleTuple = None
		self.totalChapters = 0
		self.currentChapter = 0
		self.totalTitles = 0
		self.currentTitle = 0

		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evStopped: self.__serviceStopped,
				iPlayableService.evUser: self.__timeUpdated,
				iPlayableService.evUser+1: self.__statePlay,
				iPlayableService.evUser+2: self.__statePause,
				iPlayableService.evUser+3: self.__osdFFwdInfoAvail,
				iPlayableService.evUser+4: self.__osdFBwdInfoAvail,
				iPlayableService.evUser+5: self.__osdStringAvail,
				iPlayableService.evUser+6: self.__osdAudioInfoAvail,
				iPlayableService.evUser+7: self.__osdSubtitleInfoAvail,
				iPlayableService.evUser+8: self.__chapterUpdated,
				iPlayableService.evUser+9: self.__titleUpdated,
				iPlayableService.evUser+11: self.__menuOpened,
				iPlayableService.evUser+12: self.__menuClosed,
				iPlayableService.evUser+13: self.__osdAngleInfoAvail
			})

		self["DVDPlayerDirectionActions"] = ActionMap(["DirectionActions"],
			{
				#MENU KEY DOWN ACTIONS
				"left": self.keyLeft,
				"right": self.keyRight,
				"up": self.keyUp,
				"down": self.keyDown,

				#MENU KEY REPEATED ACTIONS
				"leftRepeated": self.doNothing,
				"rightRepeated": self.doNothing,
				"upRepeated": self.doNothing,
				"downRepeated": self.doNothing,

				#MENU KEY UP ACTIONS
				"leftUp": self.doNothing,
				"rightUp": self.doNothing,
				"upUp": self.doNothing,
				"downUp": self.doNothing,
			})

		self["OkCancelActions"] = ActionMap(["OkCancelActions"],
			{
				"ok": self.keyOk,
				"cancel": self.keyCancel,
			})

		self["DVDPlayerPlaybackActions"] = HelpableActionMap(self, "DVDPlayerActions",
			{
				#PLAYER ACTIONS
				"dvdMenu": (self.enterDVDMenu, _("show DVD main menu")),
				"toggleInfo": (self.toggleInfo, _("toggle time, chapter, audio, subtitle info")),
				"nextChapter": (self.nextChapter, _("forward to the next chapter")),
				"prevChapter": (self.prevChapter, _("rewind to the previous chapter")),
				"nextTitle": (self.nextTitle, _("jump forward to the next title")),
				"prevTitle": (self.prevTitle, _("jump back to the previous title")),
				"tv": (self.askLeavePlayer, _("exit DVD player or return to file browser")),
				"dvdAudioMenu": (self.enterDVDAudioMenu, _("(show optional DVD audio menu)")),
				"AudioSelection": (self.enterAudioSelection, _("Select audio track")),
				"nextAudioTrack": (self.nextAudioTrack, _("switch to the next audio track")),
				"nextSubtitleTrack": (self.nextSubtitleTrack, _("switch to the next subtitle language")),
				"nextAngle": (self.nextAngle, _("switch to the next angle")),
				"seekBeginning": self.seekBeginning,
			}, -2)

		self["DVDPlayerColorActions"] = HelpableActionMap(self, "ColorActions",
			{
				"blue": (self.chapterZap, _("jump to chapter by number")),
			}, -2)

		self.onClose.append(self.__onClose)

		try:
			from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
			hotplugNotifier.append(self.hotplugCB)
		except:
			pass

		self.autoplay = dvd_device or dvd_filelist

		if dvd_device:
			self.physicalDVD = True
		else:
			self.scanHotplug()

		self.dvd_filelist = dvd_filelist
		self.onFirstExecBegin.append(self.opened)
		self.service = None
		self.in_menu = False
		if fileExists("/proc/stb/vmpeg/0/dst_left"):
			self.left = open("/proc/stb/vmpeg/0/dst_left", "r").read()[:-1]
			self.width = open("/proc/stb/vmpeg/0/dst_width", "r").read()[:-1]
			self.top = open("/proc/stb/vmpeg/0/dst_top", "r").read()[:-1]
			self.height = open("/proc/stb/vmpeg/0/dst_height", "r").read()[:-1]
			if self.left != "0" or self.top != "0" or self.width != "2d0" or self.height != "240":
				open("/proc/stb/vmpeg/0/dst_left", "w").write("0")
				open("/proc/stb/vmpeg/0/dst_width", "w").write("2d0")
				open("/proc/stb/vmpeg/0/dst_top", "w").write("0")
				open("/proc/stb/vmpeg/0/dst_height", "w").write("240")
				self.onClose.append(self.__restoreOSDSize)
Esempio n. 37
0
    def __init__(self, session, menu_path=""):
        instance = None
        Screen.__init__(self, session)
        if hasattr(config.usage, 'show_menupath'):
            screentitle = _("HR-Tuner Proxy for Enigma2")
            self.menu_path = menu_path
            if config.usage.show_menupath.value == 'large':
                self.menu_path += screentitle
                title = self.menu_path
                self["menu_path_compressed"] = StaticText("")
                self.menu_path += ' / '
            elif config.usage.show_menupath.value == 'small':
                title = screentitle
                condtext = ""
                if self.menu_path and not self.menu_path.endswith(' / '):
                    condtext = self.menu_path + " >"
                elif self.menu_path:
                    condtext = self.menu_path[:-3] + " >"
                self["menu_path_compressed"] = StaticText(condtext)
                self.menu_path += screentitle + ' / '
            else:
                title = screentitle
                self["menu_path_compressed"] = StaticText("")
        else:
            title = _("HR-Tuner Proxy for Enigma2")
            self.menu_path = ""
        Screen.setTitle(self, title)

        self.savedval = config.hrtunerproxy.type.value

        self.onChangedEntry = []
        self.list = []
        ConfigListScreen.__init__(self,
                                  self.list,
                                  session=session,
                                  on_change=self.onChange)

        self["information"] = Label()
        self["hinttext"] = Label()
        self["actions"] = ActionMap(
            ['ColorActions', 'OkCancelActions', 'DirectionActions'], {
                "cancel": self.keyCancel,
                "red": self.keyCancel,
                "green": self.keySave,
                "yellow": self.cleanfiles,
                "blue": self.about
            }, -2)
        self["actions"].setEnabled(False)

        self["okaction"] = ActionMap(['OkCancelActions'], {
            "ok": self.ok,
            "cancel": self.keyCancel,
        }, -2)
        self["okaction"].setEnabled(False)

        self["closeaction"] = ActionMap(['OkCancelActions', 'ColorActions'], {
            "ok": self.keyCancel,
            "cancel": self.keyCancel,
            "red": self.keyCancel
        }, -2)
        self["closeaction"].setEnabled(False)

        self["key_red"] = Button(_("Close"))
        self["key_red"].hide()
        self["button_red"] = Pixmap()
        self["button_red"].hide()
        self["key_green"] = Button()
        self["key_green"].hide()
        self["button_green"] = Pixmap()
        self["button_green"].hide()
        self["key_yellow"] = Button()
        self["key_yellow"].hide()
        self["button_yellow"] = Pixmap()
        self["button_yellow"].hide()
        self["key_blue"] = Button(_("About"))
        self["button_blue"] = Pixmap()

        self.firstrun = True

        assert HRTunerProxy_Setup.instance is None, "class is a singleton class and just one instance of this class is allowed!"
        HRTunerProxy_Setup.instance = self

        self.onLayoutFinish.append(self.LayoutFinish)
        self.onClose.append(self.__onClose)
Esempio n. 38
0
	def __init__(self, session, parent):
		Screen.__init__(self, session, parent)
		self["Title"] = Label("")
		self["Time"] = Label("")
		self["Chapter"] = Label("")
Esempio n. 39
0
    def __init__(self,
                 session,
                 title=None,
                 width=None,
                 height=None,
                 message=None,
                 message_height=None,
                 accep_label=None,
                 accep_height=None,
                 col_num=4,
                 images=[],
                 image_width=160,
                 image_height=160,
                 max_sel_items=None):
        self.iptv_title = title
        self.iptv_width = width
        self.iptv_height = height
        self.iptv_message = message
        self.iptv_message_height = message_height

        self.iptv_accep_label = accep_label
        self.iptv_accep_height = accep_height

        self.iptv_col_num = col_num
        self.iptv_row_num = len(images) / col_num
        if len(images) % col_num > 0:
            self.iptv_row_num += 1

        self.iptv_images = images
        self.iptv_image_width = image_width
        self.iptv_image_height = image_width
        self.iptv_max_sel_items = max_sel_items
        self.iptv_num_sel_items = 0
        self.iptv_images_data = None

        self.iptv_grid = []
        for x in range(self.iptv_col_num):
            self.iptv_grid.append([])
            for y in range(self.iptv_row_num):
                self.iptv_grid[x].append(None)

        self.skin = self.__prepareSkin()
        Screen.__init__(self, session)
        #self.skinName = "IPTVMultipleImageSelectorWidget"

        self.onShown.append(self.onStart)
        self.onClose.append(self.__onClose)

        # create controls
        self["title"] = Label(self.iptv_title)
        if self.iptv_message != None:
            self["message"] = Label(str(self.iptv_message))

        for idx in range(self.iptv_col_num):
            self["col_%d" %
                 idx] = IPTVImagesSelectionList(self.iptv_image_height + 20)

        if self.iptv_accep_label:
            self["accept_button"] = Label(self.iptv_accep_label)

        self["actions"] = ActionMap(
            [
                "SetupActions", "ColorActions", "WizardActions",
                "ListboxActions", "IPTVPlayerListActions"
            ], {
                "cancel": self.key_cancel,
                "ok": self.key_ok,
                "green": self.key_green,
                "read": self.key_read,
                "up": self.key_up,
                "down": self.key_down,
                "moveUp": self.key_up,
                "moveDown": self.key_down,
                "moveTop": self.key_home,
                "moveEnd": self.key_end,
                "home": self.key_home,
                "end": self.key_end,
                "pageUp": self.key_page_up,
                "pageDown": self.key_page_down,
                "left": self.key_left,
                "right": self.key_right,
            }, -2)

        self.column_index = 0
        self.row_index = 0
        self.picload = ePicLoad()
        self.picload.setPara((self.iptv_image_width, self.iptv_image_height, 1,
                              1, False, 1, "#00000000"))
        self.picload_conn = None
Esempio n. 40
0
    def __init__(self, session, params={}):

        # Skin generator
        maxWidth = 0
        pX = 40
        pY = 60
        dY = 10
        skinItems = ''
        self.icons = []
        self.list = params['list']
        self.withAcceptButton = params.get('with_accept_button', False)
        self.statusText = params.get('status_text', '')
        statusTextHight = params.get('status_text_hight', 80)
        # calcl maxWidth size
        for idx in range(len(self.list)):
            item = self.list[idx]
            if item['label_size'][0] > maxWidth:
                maxWidth = item['label_size'][0]
            if item['input_size'][0] > maxWidth:
                maxWidth = item['input_size'][0]
        maxWidth += pX * 2

        if len(self.statusText):
            skinItems = '<widget name="statustext"   position="10,%d"  zPosition="2" size="%d,%d"  valign="center" halign="center" font="Regular;22" transparent="1" />' % (
                pY + dY, maxWidth - 20, statusTextHight)
            pY += statusTextHight + dY * 2

        for idx in range(len(self.list)):
            item = self.list[idx]
            if 'icon_path' in item:
                self["cover_%d" % idx] = Cover2()
                self.icons.append({
                    'name': "cover_%d" % idx,
                    'path': item['icon_path']
                })
            else:
                self["text_%d" % idx] = Label(item.get('title', ''))
            self["input_%d" % idx] = Input(**item['input'])
            self["border_%d" % idx] = Label("")
            if item.get('useable_chars', None) is not None:
                self["input_%d" % idx].setUseableChars(item['useable_chars'])

            if 'icon_path' in item:
                skinItems += '<widget name="cover_%d" position="%d,%d" size="%d,%d" zPosition="8" />' % (
                    idx, (maxWidth - item['label_size'][0]) / 2, pY,
                    item['label_size'][0], item['label_size'][1])
            else:
                skinItems += '<widget name="text_%d" position="%d,%d" size="%d,%d" font="%s" zPosition="2" />' % (
                    idx, 10, pY, item['label_size'][0], item['label_size'][1],
                    item['label_font'])

            pY += dY + item['label_size'][1]
            skinItems += '<widget name="input_%d" position="%d,%d" size="%d,%d" font="%s" zPosition="2" />' % (
                idx, pX, pY, item['input_size'][0], item['input_size'][1],
                item['input_font'])
            skinItems += '<widget name="border_%d" position="%d,%d" size="%d,%d" font="%s" zPosition="1" transparent="0" backgroundColor="#331F93B9" />' % (
                idx, pX - 5, pY - 5, item['input_size'][0] + 10,
                item['input_size'][1] + 10, item['input_font'])
            if 0 == idx:
                self['marker'] = Cover3()
                skinItems += '<widget name="marker" zPosition="2" position="10,%d" size="16,16" transparent="1" alphatest="blend" />' % (
                    pY + (item['input_size'][1] - 16) / 2)
            skinItems += '<widget name="marker_%d" zPosition="1" position="10,%d" size="16,16" transparent="1" alphatest="blend" />' % (
                idx, pY + (item['input_size'][1] - 16) / 2)
            self['marker_%d' % idx] = Cover3()
            pY += dY * 2 + item['input_size'][1]

        if self.withAcceptButton:
            skinItems += '<widget name="accept_button"  position="10,%d"  zPosition="2" size="%d,50"  valign="center" halign="center" font="Regular;22" foregroundColor="#00FFFFFF" backgroundColor="#320F0F0F" />' % (
                pY, maxWidth - 20)
            pY += dY * 2 + 50
        self.skin = """
        <screen name="IPTVMultipleInputBox" position="center,center" size="%d,%d" title="%s">
            <widget name="key_red"   position="10,10" zPosition="2" size="%d,35" valign="center" halign="left"   font="Regular;22" transparent="1" foregroundColor="red" />
            <widget name="key_ok"    position="10,10" zPosition="2" size="%d,35" valign="center" halign="center" font="Regular;22" transparent="1" foregroundColor="white" />
            <widget name="key_green" position="10,10" zPosition="2" size="%d,35" valign="center" halign="right"  font="Regular;22" transparent="1" foregroundColor="green" />
            %s
        </screen>
        """ % (maxWidth, pY, params.get('title', _("Input")), maxWidth - 20,
               maxWidth - 20, maxWidth - 20, skinItems)

        self["key_green"] = Label(params.get('accep_label', _("Save")))
        self["key_ok"] = Label(_("OK"))
        self["key_red"] = Label(_("Cancel"))
        if len(self.statusText):
            self["statustext"] = Label(str(self.statusText))
        if self.withAcceptButton:
            self["accept_button"] = Label(
                params.get('accep_label', _("Verify")))

        self.params = params

        Screen.__init__(self, session)
        self.onShown.append(self.onStart)
        self.onClose.append(self.__onClose)

        self["actions"] = NumberActionMap(
            [
                "ColorActions", "WizardActions", "InputBoxActions",
                "InputAsciiActions", "KeyboardInputActions"
            ], {
                "gotAsciiCode": self.gotAsciiCode,
                "green": self.keySave,
                "ok": self.keyOK,
                "red": self.keyCancel,
                "back": self.keyCancel,
                "left": self.keyLeft,
                "right": self.keyRight,
                "up": self.keyUp,
                "down": self.keyDown,
                "right": self.keyRight,
                "home": self.keyHome,
                "end": self.keyEnd,
                "deleteForward": self.keyDelete,
                "deleteBackward": self.keyBackspace,
                "tab": self.keyTab,
                "toggleOverwrite": self.keyInsert,
                "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
            }, -1)

        self.idx = 0
        self.activeInput = "input_0"
        self.markerPixmap = [
            LoadPixmap(GetIconDir('radio_button_on.png')),
            LoadPixmap(GetIconDir('radio_button_off.png'))
        ]

        self.started = False
Esempio n. 41
0
    def __init__(self, session, args=0):

        assert not slManager.instance, "only one slManager instance is allowed!"
        slManager.instance = self
        self.skin = slManager.skin

        Screen.__init__(self, session)

        self.setTitle(_('Sat-Lodge Manager by lululla V. %s' % Version))
        self.session = session

        self.index = 0
        self.emulist = []
        self.namelist = []
        self.oldService = self.session.nav.getCurrentlyPlayingServiceReference(
        )
        self["actions"] = ActionMap(
            ["OkCancelActions", "ColorActions"], {
                "ok": self.action,
                "cancel": self.close,
                "yellow": self.download,
                "green": self.action,
                "blue": self.slpanel,
                "red": self.stop,
            }, -1)
        self["key_green"] = Button(_("Start"))
        # self["key_green2"] = Button(_("ReStart"))

        self["key_blue"] = Button(_("SatLodge Panel"))
        self['key_blue'].hide()
        if fileExists(
                '/usr/lib/enigma2/python/Plugins/SatLodge/slPanel/plugin.pyo'):
            self["key_blue"].show()

        self["key_yellow"] = Button(_("Download"))
        self["key_red"] = Button(_("Stop"))
        self['version'] = Label(_('V. %s' % Version))
        self['maintener'] = Label(_('by ))^^(('))
        self['team'] = Label(_('..:: Sat-Lodge Manager ::..'))
        self['info'] = Label()
        self.currCam = self.readCurrent()
        self.softcamslist = []
        self['desc'] = Label()
        self['ecminfo'] = Label(_('Ecm Info'))
        # self["list"] = MenuList(self.softcamslist)
        self["list"] = m2list([])
        self.timer = eTimer()
        self['desc'].setText(_('Scanning and retrieval list softcam ...'))
        try:
            self.timer.callback.append(self.cgdesc)
        except:
            self.timer_conn = self.timer.timeout.connect(self.cgdesc)
        self.timer.start(200, 1)
        self.readScripts()
        self.ecminfo = GetEcmInfo()
        (newEcmFound, ecmInfo) = self.ecminfo.getEcm()
        self["info"] = ScrollLabel("".join(ecmInfo))
        self.EcmInfoPollTimer = eTimer()
        try:
            self.EcmInfoPollTimer.callback.append(self.setEcmInfo)
        except:
            self.timer_conn = self.EcmInfoPollTimer.timeout.connect(
                self.setEcmInfo)
        self.EcmInfoPollTimer.start(100)
Esempio n. 42
0
class PositionerSetup(Screen):
	skin = """
		<screen position="100,100" size="560,400" title="Positioner setup..." >
			<widget name="list" position="100,0" size="350,155" />

			<widget name="red" position="0,155" size="140,80" backgroundColor="red" halign="center" valign="center" font="Regular;21" />
			<widget name="green" position="140,155" size="140,80" backgroundColor="green" halign="center" valign="center" font="Regular;21" />
			<widget name="yellow" position="280,155" size="140,80" backgroundColor="yellow" halign="center" valign="center" font="Regular;21" />
			<widget name="blue" position="420,155" size="140,80" backgroundColor="blue" halign="center" valign="center" font="Regular;21" />

			<widget name="snr_db" position="60,245" size="150,22" halign="center" valign="center" font="Regular;21" />
			<eLabel text="SNR:" position="0,270" size="60,22" font="Regular;21" />
			<eLabel text="BER:" position="0,295" size="60,22" font="Regular;21" />
			<eLabel text="Lock:" position="0,320" size="60,22" font="Regular;21" />
			<widget name="snr_percentage" position="220,270" size="60,22" font="Regular;21" />
			<widget name="ber_value" position="220,295" size="60,22" font="Regular;21" />
			<widget name="lock_state" position="60,320" size="150,22" font="Regular;21" />
			<widget name="snr_bar" position="60,270" size="150,22" />
			<widget name="ber_bar" position="60,295" size="150,22" />

			<eLabel text="Frequency:" position="300,245" size="120,22" font="Regular;21" />
			<eLabel text="Symbolrate:" position="300,270" size="120,22" font="Regular;21" />
			<eLabel text="FEC:" position="300,295" size="120,22" font="Regular;21" />
			<widget name="frequency_value" position="420,245" size="120,22" font="Regular;21" />
			<widget name="symbolrate_value" position="420,270" size="120,22" font="Regular;21" />
			<widget name="fec_value" position="420,295" size="120,22" font="Regular;21" />
		</screen>"""
	def __init__(self, session, feid):
		self.skin = PositionerSetup.skin
		Screen.__init__(self, session)
		self.feid = feid
		self.oldref = None

		cur = { }
		if not self.openFrontend():
			self.oldref = session.nav.getCurrentlyPlayingServiceReference()
			service = session.nav.getCurrentService()
			feInfo = service and service.frontendInfo()
			if feInfo:
				cur = feInfo.getTransponderData(True)
			del feInfo
			del service
			session.nav.stopService() # try to disable foreground service
			if not self.openFrontend():
				if session.pipshown: # try to disable pip
					service = self.session.pip.pipservice
					feInfo = service and service.frontendInfo()
					if feInfo:
						cur = feInfo.getTransponderData()
					del feInfo
					del service
					session.pipshown = False
					session.deleteDialog(session.pip)
					del session.pip
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen

		self.frontendStatus = { }
		self.diseqc = Diseqc(self.frontend)
		self.tuner = Tuner(self.frontend, True) #True means we dont like that the normal sec stuff sends commands to the rotor!

		tp = ( cur.get("frequency", 0) / 1000,
			cur.get("symbol_rate", 0) / 1000,
			cur.get("polarization", eDVBFrontendParametersSatellite.Polarisation_Horizontal),
			cur.get("fec_inner", eDVBFrontendParametersSatellite.FEC_Auto),
			cur.get("inversion", eDVBFrontendParametersSatellite.Inversion_Unknown),
			cur.get("orbital_position", 0),
			cur.get("system", eDVBFrontendParametersSatellite.System_DVB_S),
			cur.get("modulation", eDVBFrontendParametersSatellite.Modulation_QPSK),
			cur.get("rolloff", eDVBFrontendParametersSatellite.RollOff_alpha_0_35),
			cur.get("pilot", eDVBFrontendParametersSatellite.Pilot_Unknown))

		self.tuner.tune(tp)
		self.createConfig()

		self.isMoving = False
		self.stopOnLock = False

		self.red = Label("")
		self["red"] = self.red
		self.green = Label("")
		self["green"] = self.green
		self.yellow = Label("")
		self["yellow"] = self.yellow
		self.blue = Label("")
		self["blue"] = self.blue

		self.list = []
		self["list"] = ConfigList(self.list)
		self.createSetup()

		self["snr_db"] = TunerInfo(TunerInfo.SNR_DB, statusDict = self.frontendStatus)
		self["snr_percentage"] = TunerInfo(TunerInfo.SNR_PERCENTAGE, statusDict = self.frontendStatus)
		self["ber_value"] = TunerInfo(TunerInfo.BER_VALUE, statusDict = self.frontendStatus)
		self["snr_bar"] = TunerInfo(TunerInfo.SNR_BAR, statusDict = self.frontendStatus)
		self["ber_bar"] = TunerInfo(TunerInfo.BER_BAR, statusDict = self.frontendStatus)
		self["lock_state"] = TunerInfo(TunerInfo.LOCK_STATE, statusDict = self.frontendStatus)

		self["frequency_value"] = Label("")
		self["symbolrate_value"] = Label("")
		self["fec_value"] = Label("")

		self["actions"] = ActionMap(["DirectionActions", "OkCancelActions", "ColorActions"],
		{
			"ok": self.go,
			"cancel": self.keyCancel,
			"up": self.up,
			"down": self.down,
			"left": self.left,
			"right": self.right,
			"red": self.redKey,
			"green": self.greenKey,
			"yellow": self.yellowKey,
			"blue": self.blueKey,
		}, -1)

		self.updateColors("tune")

		self.statusTimer = eTimer()
		self.statusTimer_conn = self.statusTimer.timeout.connect(self.updateStatus)
		self.statusTimer.start(50, True)
		self.onClose.append(self.__onClose)

	def __onClose(self):
		self.session.nav.playService(self.oldref)

	def restartPrevService(self, yesno):
		if yesno:
			if self.frontend:
				self.frontend = None
				del self.raw_channel
		else:
			self.oldref=None
		self.close(None)

	def keyCancel(self):
		if self.oldref:
			self.session.openWithCallback(self.restartPrevService, MessageBox, _("Zap back to service before positioner setup?"), MessageBox.TYPE_YESNO)
		else:
			self.restartPrevService(False)

	def openFrontend(self):
		res_mgr = eDVBResourceManager.getInstance()
		if res_mgr:
			self.raw_channel = res_mgr.allocateRawChannel(self.feid)
			if self.raw_channel:
				self.frontend = self.raw_channel.getFrontend()
				if self.frontend:
					return True
				else:
					print "getFrontend failed"
			else:
				print "getRawChannel failed"
		else:
			print "getResourceManager instance failed"
		return False

	def createConfig(self):
		self.positioner_tune = ConfigNothing()
		self.positioner_move = ConfigNothing()
		self.positioner_finemove = ConfigNothing()
		self.positioner_limits = ConfigNothing()
		self.positioner_goto0 = ConfigNothing()
		storepos = []
		for x in range(1,255):
			storepos.append(str(x))
		self.positioner_storage = ConfigSelection(choices = storepos)

	def createSetup(self):
		self.list.append((_("Tune"), self.positioner_tune, "tune"))
		self.list.append((_("Positioner movement"), self.positioner_move, "move"))
		self.list.append((_("Positioner fine movement"), self.positioner_finemove, "finemove"))
		self.list.append((_("Set limits"), self.positioner_limits, "limits"))
		self.list.append((_("Positioner storage"), self.positioner_storage, "storage"))
		self.list.append((_("Goto 0"), self.positioner_goto0, "goto0"))
		self["list"].l.setList(self.list)

	def go(self):
		pass

	def getCurrentConfigPath(self):
		return self["list"].getCurrent()[2]

	def up(self):
		if not self.isMoving:
			self["list"].instance.moveSelection(self["list"].instance.moveUp)
			self.updateColors(self.getCurrentConfigPath())

	def down(self):
		if not self.isMoving:
			self["list"].instance.moveSelection(self["list"].instance.moveDown)
			self.updateColors(self.getCurrentConfigPath())

	def left(self):
		self["list"].handleKey(KEY_LEFT)

	def right(self):
		self["list"].handleKey(KEY_RIGHT)

	def updateColors(self, entry):
		if entry == "tune":
			self.red.setText(_("Tune"))
			self.green.setText("")
			self.yellow.setText("")
			self.blue.setText("")
		elif entry == "move":
			if self.isMoving:
				self.red.setText(_("Stop"))
				self.green.setText(_("Stop"))
				self.yellow.setText(_("Stop"))
				self.blue.setText(_("Stop"))
			else:
				self.red.setText(_("Move west"))
				self.green.setText(_("Search west"))
				self.yellow.setText(_("Search east"))
				self.blue.setText(_("Move east"))
		elif entry == "finemove":
			self.red.setText("")
			self.green.setText(_("Step west"))
			self.yellow.setText(_("Step east"))
			self.blue.setText("")
		elif entry == "limits":
			self.red.setText(_("Limits off"))
			self.green.setText(_("Limit west"))
			self.yellow.setText(_("Limit east"))
			self.blue.setText(_("Limits on"))
		elif entry == "storage":
			self.red.setText("")
			self.green.setText(_("Store position"))
			self.yellow.setText(_("Goto position"))
			self.blue.setText("")
		elif entry == "goto0":
			self.red.setText(_("Goto 0"))
			self.green.setText("")
			self.yellow.setText("")
			self.blue.setText("")
		else:
			self.red.setText("")
			self.green.setText("")
			self.yellow.setText("")
			self.blue.setText("")

	def redKey(self):
		entry = self.getCurrentConfigPath()
		if entry == "move":
			if self.isMoving:
				self.diseqccommand("stop")
				self.isMoving = False
				self.stopOnLock = False
			else:
				self.diseqccommand("moveWest", 0)
				self.isMoving = True
			self.updateColors("move")
		elif entry == "limits":
			self.diseqccommand("limitOff")
		elif entry == "tune":
			fe_data = { }
			self.frontend.getFrontendData(fe_data)
			self.frontend.getTransponderData(fe_data, True)
			feparm = self.tuner.lastparm.getDVBS()
			fe_data["orbital_position"] = feparm.orbital_position
			self.session.openWithCallback(self.tune, TunerScreen, self.feid, fe_data)
		elif entry == "goto0":
			print "move to position 0"
			self.diseqccommand("moveTo", 0)

	def greenKey(self):
		entry = self.getCurrentConfigPath()
		if entry == "move":
			if self.isMoving:
				self.diseqccommand("stop")
				self.isMoving = False
				self.stopOnLock = False
			else:
				self.isMoving = True
				self.stopOnLock = True
				self.diseqccommand("moveWest", 0)
			self.updateColors("move")
		elif entry == "finemove":
			print "stepping west"
			self.diseqccommand("moveWest", 0xFF) # one step
		elif entry == "storage":
			print "store at position", int(self.positioner_storage.value)
			self.diseqccommand("store", int(self.positioner_storage.value))

		elif entry == "limits":
			self.diseqccommand("limitWest")

	def yellowKey(self):
		entry = self.getCurrentConfigPath()
		if entry == "move":
			if self.isMoving:
				self.diseqccommand("stop")
				self.isMoving = False
				self.stopOnLock = False
			else:
				self.isMoving = True
				self.stopOnLock = True
				self.diseqccommand("moveEast", 0)
			self.updateColors("move")
		elif entry == "finemove":
			print "stepping east"
			self.diseqccommand("moveEast", 0xFF) # one step
		elif entry == "storage":
			print "move to position", int(self.positioner_storage.value)
			self.diseqccommand("moveTo", int(self.positioner_storage.value))
		elif entry == "limits":
			self.diseqccommand("limitEast")

	def blueKey(self):
		entry = self.getCurrentConfigPath()
		if entry == "move":
			if self.isMoving:
				self.diseqccommand("stop")
				self.isMoving = False
				self.stopOnLock = False
			else:
				self.diseqccommand("moveEast", 0)
				self.isMoving = True
			self.updateColors("move")
			print "moving east"
		elif entry == "limits":
			self.diseqccommand("limitOn")

	def diseqccommand(self, cmd, param = 0):
		self.diseqc.command(cmd, param)
		self.tuner.retune()

	def updateStatus(self):
		if self.frontend:
			self.frontendStatus.clear()
			self.frontend.getFrontendStatus(self.frontendStatus)
		self["snr_db"].update()
		self["snr_percentage"].update()
		self["ber_value"].update()
		self["snr_bar"].update()
		self["ber_bar"].update()
		self["lock_state"].update()
		transponderdata = ConvertToHumanReadable(self.tuner.getTransponderData(), "DVB-S")
		self["frequency_value"].setText(str(transponderdata.get("frequency")))
		self["symbolrate_value"].setText(str(transponderdata.get("symbol_rate")))
		self["fec_value"].setText(str(transponderdata.get("fec_inner")))
		if self.frontendStatus.get("tuner_locked", 0) == 1 and self.isMoving and self.stopOnLock:
			self.diseqccommand("stop")
			self.isMoving = False
			self.stopOnLock = False
			self.updateColors(self.getCurrentConfigPath())
		self.statusTimer.start(50, True)

	def tune(self, transponder):
		if transponder is not None:
			self.tuner.tune(transponder)
Esempio n. 43
0
class Ipkg(Screen):
	def __init__(self, session, cmdList=None):
		if not cmdList: cmdList = []
		Screen.__init__(self, session)

		self.cmdList = cmdList

		self.sliderPackages = {}

		self.slider = Slider(0, len(cmdList))
		self["slider"] = self.slider
		self.activityslider = Slider(0, 100)
		self["activityslider"] = self.activityslider
		self.status = Label(_("Preparing... Please wait"))
		self["status"] = self.status
		self.package = Label()
		self["package"] = self.package

		self.packages = 0
		self.error = 0
		self.processed_packages = []

		self.activity = 0
		self.activityTimer = eTimer()
		self.activityTimer.callback.append(self.doActivityTimer)
		#self.activityTimer.start(100, False)

		self.ipkg = IpkgComponent()
		self.ipkg.addCallback(self.ipkgCallback)

		self.runningCmd = None
		self.runNextCmd()

		self["actions"] = ActionMap(["WizardActions"],
		{
			"ok": self.exit,
			"back": self.exit
		}, -1)

	def runNextCmd(self):
		if self.runningCmd is None:
			self.runningCmd = 0
		else:
			self.runningCmd += 1
		print len(self.cmdList), self.runningCmd
		if len(self.cmdList) - 1 < self.runningCmd:
			self.activityslider.setValue(0)
			self.slider.setValue(len(self.cmdList))

			self.package.setText("")
			self.status.setText(ngettext("Done - Installed, upgraded or removed %d package (%s)", "Done - Installed, upgraded or removed %d packages (%s)", self.packages) % (self.packages, ngettext("with %d error", "with %d errors", self.error) % self.error))
			return False
		else:
			cmd = self.cmdList[self.runningCmd]
			self.slider.setValue(self.runningCmd)
			self.ipkg.startCmd(cmd[0], args = cmd[1])
			self.startActivityTimer()

	def doActivityTimer(self):
		if not self.ipkg.isRunning():
			self.stopActivityTimer()
		else:
			self.activity += 1
			if self.activity == 100:
				self.activity = 0
			self.activityslider.setValue(self.activity)

	def startActivityTimer(self):
		self.activityTimer.start(100, False)

	def stopActivityTimer(self):
		self.activityTimer.stop()

	def ipkgCallback(self, event, param):
		if event == IpkgComponent.EVENT_DOWNLOAD:
			self.status.setText(_("Downloading"))
		elif event == IpkgComponent.EVENT_UPGRADE:
			if self.sliderPackages.has_key(param):
				self.slider.setValue(self.sliderPackages[param])
			self.package.setText(param)
			self.status.setText(_("Upgrading"))
			if not param in self.processed_packages:
				self.processed_packages.append(param)
				self.packages += 1
		elif event == IpkgComponent.EVENT_INSTALL:
			self.package.setText(param)
			self.status.setText(_("Installing"))
			if not param in self.processed_packages:
				self.processed_packages.append(param)
				self.packages += 1
		elif event == IpkgComponent.EVENT_REMOVE:
			self.package.setText(param)
			self.status.setText(_("Removing"))
			if not param in self.processed_packages:
				self.processed_packages.append(param)
				self.packages += 1
		elif event == IpkgComponent.EVENT_CONFIGURING:
			self.package.setText(param)
			self.status.setText(_("Configuring"))
		elif event == IpkgComponent.EVENT_ERROR:
			self.error += 1
		elif event == IpkgComponent.EVENT_DONE:
			self.runNextCmd()
		elif event == IpkgComponent.EVENT_MODIFIED:
			self.session.openWithCallback(
				self.modificationCallback,
				MessageBox,
				_("A configuration file (%s) was modified since Installation.\nDo you want to keep your version?") % param
			)

	def modificationCallback(self, res):
		self.ipkg.write(res and "N" or "Y")

	def exit(self):
		if not self.ipkg.isRunning():
			self.close()
Esempio n. 44
0
    def __init__(self, session):
        Screen.__init__(self, session)

        self["actions"] = NumberActionMap(
            ["NumberActions", "RassInteractiveActions"], {
                "exit": self.close,
                "0": lambda x: self.numPressed(0),
                "1": lambda x: self.numPressed(1),
                "2": lambda x: self.numPressed(2),
                "3": lambda x: self.numPressed(3),
                "4": lambda x: self.numPressed(4),
                "5": lambda x: self.numPressed(5),
                "6": lambda x: self.numPressed(6),
                "7": lambda x: self.numPressed(7),
                "8": lambda x: self.numPressed(8),
                "9": lambda x: self.numPressed(9),
                "nextPage": self.nextPage,
                "prevPage": self.prevPage,
                "nextSubPage": self.nextSubPage,
                "prevSubPage": self.prevSubPage
            })

        self.__event_tracker = ServiceEventTracker(
            screen=self,
            eventmap={
                iPlayableService.evUpdatedRassInteractivePicMask:
                self.recvRassInteractivePicMaskChanged
            })

        self["subpages_1"] = Pixmap()
        self["subpages_2"] = Pixmap()
        self["subpages_3"] = Pixmap()
        self["subpages_4"] = Pixmap()
        self["subpages_5"] = Pixmap()
        self["subpages_6"] = Pixmap()
        self["subpages_7"] = Pixmap()
        self["subpages_8"] = Pixmap()
        self["subpages_9"] = Pixmap()
        self["Marker"] = Label(">")

        self.subpage = {
            1: self["subpages_1"],
            2: self["subpages_2"],
            3: self["subpages_3"],
            4: self["subpages_4"],
            5: self["subpages_5"],
            6: self["subpages_6"],
            7: self["subpages_7"],
            8: self["subpages_8"],
            9: self["subpages_9"]
        }

        self.subpage_png = {
            1:
            LoadPixmap(
                resolveFilename(SCOPE_ACTIVE_SKIN, "icons/rass_page1.png")),
            2:
            LoadPixmap(
                resolveFilename(SCOPE_ACTIVE_SKIN, "icons/rass_page2.png")),
            3:
            LoadPixmap(
                resolveFilename(SCOPE_ACTIVE_SKIN, "icons/rass_page3.png")),
            4:
            LoadPixmap(
                resolveFilename(SCOPE_ACTIVE_SKIN, "icons/rass_page4.png"))
        }

        self.current_page = 0
        self.current_subpage = 0
        self.showRassPage(0, 0)
        self.onLayoutFinish.append(self.updateSubPagePixmaps)
Esempio n. 45
0
	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
		})
Esempio n. 46
0
 def __init__(self, session):
     self.session = session
     from Skin.Main import *
     self.skin = skin
     self.skin_path = resolveFilename(SCOPE_PLUGINS, "Extensions/NGsetting")
     Screen.__init__(self, session)									
     self["actions"]  = ActionMap(["OkCancelActions", "ShortcutActions", "WizardActions", "ColorActions", "SetupActions", "NumberActions", "MenuActions", "HelpActions", "EPGSelectActions"], {
       "ok"    : self.keyOK,
       "up"    : self.keyUp,
       "down"  : self.keyDown,
       "blue"  : self.Auto,		
       "green"  : self.Lcn,	
       "yellow"  : self.Select,				  
       "cancel": self.exitplug,
       "left"  : self.keyRightLeft,
       "right" : self.keyRightLeft,							
       "red" : self.exitplug   							
     }, -1)							                        
     self['autotimer'] = Label("")  
     self['namesat'] = Label("" )  
     self['text'] = Label("" ) 			
     self['dataDow'] = Label("" )			
     self['Green'] = Pixmap()  
     self['Blue'] = Pixmap()  	
     self['Yellow'] = Pixmap() 			
     self['Green'].hide()	 
     self['Yellow'].show()	
     self['Blue'].show()				
     self["Key_Lcn"] = Label('')
     self.LcnOn = False			
     if os.path.exists(resolveFilename(SCOPE_PLUGINS, 'Extensions/NGsetting/Moduli/NGsetting/Date')) and os.path.exists('/etc/enigma2/lcndb'):		
       self['Key_Lcn'].setText(_("Lcn"))	
       self.LcnOn = True
       self['Green'].show()
     self["Key_Red"] = Label(_("Exit"))
     self["Key_Green"] = Label(_("Setting Installed:"))	
     self["Key_Personal"] = Label("")			
     AutoTimer, NameSat, Data, Type, Personal, DowDate = Load()		
     self['A'] = MenuListiSettingE2A([])
     self['B'] = MenuListiSettingE2([])    
     self["B"].selectionEnabled(1)			
     self["A"].selectionEnabled(1)		
     self.currentlist = 'B'	
     self.ServerOn = True		
     self.DubleClick = True			
     self.MenuA()	
     self.List = DownloadSetting()			
     self.MenuB()	
     self.iTimer = eTimer()				
     self.iTimer.callback.append(self.keyRightLeft) 			
     self.iTimer.start(1000, True)
     self.iTimer1 = eTimer()				
     self.iTimer1.callback.append(self.StartSetting) 
     self.Message = eTimer()				
     self.Message.callback.append(self.MessagePlugin) 
     self.OnWriteAuto = eTimer()				
     self.OnWriteAuto.callback.append(self.WriteAuto) 
     self.StopAutoWrite = False			
     self.ExitPlugin = eTimer()				
     self.ExitPlugin.callback.append(self.PluginClose) 			
     self.Reload = eTimer()				
     self.Reload.callback.append(self.ReloadGui) 			
     self.onShown.append(self.ReturnSelect)
     self.onShown.append(self.Info)	
     self.VersPlugin = Plugin()	
     if self.VersPlugin:
       if self.VersPlugin[0][1] != Version:
         self.Message.start(2000, True)
Esempio n. 47
0
File: plugin.py Progetto: aassww/xta
class MenuStart(Screen):

    def __init__(self, session):
        self.session = session
        path = '/usr/lib/enigma2/python/Plugins/Extensions/iSkin/Skin/Main.xml'
        with open(path, 'r') as f:
            self.skin = f.read()
            f.close()
        mdom = xml.etree.cElementTree.parse(path)
        for x in mdom.getroot():
            if x.tag == 'widget' and x.get('name') == 'cover':
                Size = x.get('size').split(',')
                self.SizeY = int(Size[0])
                self.SizeX = int(Size[1])

        Screen.__init__(self, session)
        self['Key_Red'] = Label(_('Exit'))
        self['Key_Green'] = Label('')
        self['Key_Yellow'] = Label('')
        self['ButtonYellow'] = Pixmap()
        self['ButtonYellow'].hide()
        if os.path.exists('/usr/lib/enigma2/python/Components/Converter/TestConnection.pyo'):
            self['Key_Yellow'].setText(_('Config Connection'))
            self['ButtonYellow'].show()
        self.Region = Label('')
        self['Key_Region'] = self.Region
        self.Key_Blu = Label('')
        self['Key_Blu'] = self.Key_Blu
        self['SkinSelect'] = iMenuList([])
        self.isMoving = False
        self['cover'] = Pixmap()
        self.Loop = eTimer()
        self.Loop.stop()
        self.Loop.callback.append(self.Cover)
        self['setupActions'] = ActionMap(['SkinActionSetup'], {'blue': self.keyBlue,
         'green': self.keyGreen,
         'yellow': self.keyYellow,
         'ok': self.keyOK,
         'up': self.up,
         'down': self.down,
         'red': self.close,
         'cancel': self.close}, -1)
        self.onLayoutFinish.append(self.layoutFinished)
        self.onShown.append(self.SetButtonWeather)

    def SetButtonWeather(self):
        if os.path.exists('/usr/lib/enigma2/python/Plugins/Extensions/iSkin/Weather/Weather.pyo'):
            self.Key_Blu.setText('Config Weather')
            if os.path.exists('/usr/lib/enigma2/python/Plugins/Extensions/iSkin/Weather/Config/Region_id'):
                jRegion_id = open('/usr/lib/enigma2/python/Plugins/Extensions/iSkin/Weather/Config/Region_id').read()
                self.Region.setText(jRegion_id)

    def keyYellow(self):
        if os.path.exists('/usr/lib/enigma2/python/Plugins/Extensions/iSkin/Connection/Connection.pyo'):
            try:
                self.session.open(ConfigConnection)
            except:
                pass

    def keyBlue(self):
        try:
            self.session.open(WeatherSearch)
        except:
            pass

    def keyGreen(self):
        try:
            self.session.open(MeteoMain)
        except:
            pass

    def Cover(self):
        try:
            self.Loop.stop()
        except:
            pass

        try:
            png = loadPic(str(self.getCurrentConfigPath()), self.SizeY, self.SizeX, 0, 0, 0, 1)
            self['cover'].instance.setPixmap(png)
            self['cover'].show()
        except:
            pass

    def getCurrentConfigPath(self):
        return self['SkinSelect'].getCurrent()[0][1]

    def up(self):
        if not self.isMoving:
            self['SkinSelect'].instance.moveSelection(self['SkinSelect'].instance.moveUp)
            self.Loop.start(100, True)

    def down(self):
        if not self.isMoving:
            self['SkinSelect'].instance.moveSelection(self['SkinSelect'].instance.moveDown)
            self.Loop.start(100, True)

    def layoutFinished(self):
        mdom = xml.etree.cElementTree.parse(os.path.dirname(sys.modules[__name__].__file__) + '/Config/SkinSetup.xml')
        self.SkinSelect = []
        for x in mdom.getroot():
            if x.tag == 'ruleset':
                self.SkinSelect.append(self.ListEntry(x.get('name'), x.get('Icon')))

        self.SkinSelect.sort(key=lambda t: tuple(t[0][0].lower()))
        self['SkinSelect'].setList(self.SkinSelect)
        self.Loop.start(100, True)

    def ListEntry(self, name, jpg):
        res = [(name, jpg)]
        icon = '/usr/lib/enigma2/python/Plugins/Extensions/iSkin/Skin/no_icon.png'
        res.append(MultiContentEntryPixmapAlphaTest(pos=(0, 1), size=(75, 40), png=loadPNG(icon)))
        res.append(MultiContentEntryText(pos=(70, 4), size=(600, 30), font=0, text=name, flags=RT_HALIGN_LEFT))
        return res

    def keyOK(self):
        exist = self['SkinSelect'].getCurrent()
        if exist == None:
            return
        selection = self['SkinSelect'].getCurrent()[0][0]
        self.session.open(ConfigSkin, selection)
Esempio n. 48
0
    def __init__(self, session):
        # get framebuffer resolution...
        desk = getDesktop(0)
        wdesktop = int(desk.size().width())

        # cellsize depends from framebuffer resolution...
        if wdesktop == 720:
            CELL_SIZE = 20
        elif wdesktop == 1024:
            CELL_SIZE = 30
        elif wdesktop == 1280:
            CELL_SIZE = 40
        else:
            CELL_SIZE = 20

        # calculate skindata...
        CELL_OFFSET = 2
        cellfield = XMAX * CELL_SIZE + (XMAX - 1) * CELL_OFFSET
        CW = 2 * cellfield + 150  # canvas w
        CH = cellfield  # canvas h
        X0_OFFSET = 0  # xoffset cellfield box
        X1_OFFSET = cellfield + 150  # xoffset cellfield you
        W = CW + 10  # window w
        H = CH + 40  # window h
        WX = cellfield + 10  # widgets xoffset
        W0Y = 25  # widget0 yoffset
        W1Y = cellfield - 116  # widget1 yoffset
        W2Y = cellfield - 66  # widget2 yoffset
        W3Y = cellfield - 16  # widget3 yoffset

        # set skin...
        Schiffe.skin = """
			<screen position="center,center" size="%d,%d" title="Schiffe versenken %s" >
				<widget source="Canvas" render="Canvas" position="5,20" size="%d,%d" />
				<widget name="message" position="%d,%d" size="140,40" valign="center" halign="center" font="Regular;21"/>
				<ePixmap name="green"    position="%d,%d"   zPosition="4" size="140,40" pixmap="buttons/green.png" transparent="1" alphatest="on" />
				<ePixmap name="blue" position="%d,%d" zPosition="4" size="140,40" pixmap="buttons/blue.png" transparent="1" alphatest="on" />
				<ePixmap name="red"   position="%d,%d" zPosition="4" size="140,40" pixmap="buttons/red.png" transparent="1" alphatest="on" />
				<widget name="key_green"    position="%d,%d"   zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
				<widget name="key_blue" position="%d,%d" zPosition="5" size="140,40" valign="center" halign="center"  font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
				<widget name="key_red"   position="%d,%d" zPosition="5" size="140,40" valign="center" halign="center" font="Regular;21" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-1,-1" />
			</screen>""" % (W, H, VERSION, CW, CH, WX, W0Y, WX, W1Y, WX, W2Y, WX, W3Y,
                   WX, W1Y, WX, W2Y, WX, W3Y)

        # get window background color - find xml for actual skin...
        filename = resolveFilename(SCOPE_CURRENT_SKIN, "skin.xml")
        actualSkin = xml.etree.cElementTree.parse(filename).getroot()

        # get colors from skin and write to dictionary
        colorNames = dict()
        for c in actualSkin.findall("colors"):
            for color in c.findall("color"):
                get_attr = color.attrib.get
                name = get_attr("name")
                color = get_attr("value")
                if name and color:
                    colorNames[name] = color

        # find colors for skinned window...
        for windowstyle in actualSkin.findall("windowstyle"):
            # look or skinned window...
            if windowstyle.attrib.get("id") == "0":
                for color in windowstyle.findall("color"):
                    get_attr = color.attrib.get
                    type = get_attr("name")
                    color = get_attr("color")
                    # is it a "named" color?
                    if color[0] != '#':
                        # is "named" color, have to look in dictionary...
                        color = colorNames[color]
                    # at least get the background color...
                    if type == "Background":
                        bgcolor = int(color[1:], 0x10)
        if not bgcolor:
            bgcolor = RGB(0, 0, 0)

        self.skin = Schiffe.skin
        Screen.__init__(self, session)
        self["Canvas"] = CanvasSource()
        self["message"] = Label(_("Status"))
        self["key_green"] = Button(_("new game"))
        self["key_blue"] = Button(_("solve game"))
        self["key_red"] = Button(_("quit game"))

        self.cnt = 0
        self.timer = eTimer()
        self.timer.callback.append(self.timerHandler)

        self.message = 0

        self["actions"] = ActionMap(
            ["WizardActions", "ColorActions", "SetupActions"], {
                "ok": self.ok_pressed,
                "up": self.up_pressed,
                "down": self.down_pressed,
                "left": self.left_pressed,
                "right": self.right_pressed,
                "red": self.quit_game,
                "green": self.new_game,
                "blue": self.solve_game,
                "cancel": self.quit_game
            })

        # fill canvas with background color...
        self["Canvas"].fill(0, 0, CW, CH, bgcolor)

        self.you = []
        self.box = []
        self.youCells = []
        self.boxCells = []

        for j in range(YMAX):
            for i in range(XMAX):
                cell = GameCell(self["Canvas"],
                                i * (CELL_SIZE + CELL_OFFSET) + X0_OFFSET,
                                j * (CELL_SIZE + CELL_OFFSET), CELL_SIZE,
                                CELL_SIZE)
                self.boxCells.append(cell)

        for j in range(YMAX):
            for i in range(XMAX):
                cell = GameCell(self["Canvas"],
                                i * (CELL_SIZE + CELL_OFFSET) + X1_OFFSET,
                                j * (CELL_SIZE + CELL_OFFSET), CELL_SIZE,
                                CELL_SIZE)
                self.youCells.append(cell)

        self.onLayoutFinish.append(self.load_game)
    def __init__(self, session, providers, pcallback=None, noosd=False):
        from Components.Sources.StaticText import StaticText
        from Components.Sources.Progress import Progress
        if (getDesktop(0).size().width() < 800):
            skin = "%s/skins/downloader_sd.xml" % os.path.dirname(
                sys.modules[__name__].__file__)
            self.isHD = 0
        else:
            skin = "%s/skins/downloader_hd.xml" % os.path.dirname(
                sys.modules[__name__].__file__)
            self.isHD = 1
        f = open(skin, "r")
        self.skin = f.read()
        f.close()
        Screen.__init__(self, session)

        self.session = session

        self["background"] = Pixmap()
        self["action"] = Label(_("Starting downloader"))
        self["status"] = Label("")
        self["progress"] = ProgressBar()
        self["progress"].hide()
        self["summary_action"] = StaticText(_("Starting downloader"))
        self["summary_status"] = StaticText()
        self["summary_progress"] = Progress()
        self["actions"] = NumberActionMap(["WizardActions", "InputActions"],
                                          {"back": self.quit}, -1)

        self.__event_tracker = ServiceEventTracker(
            screen=self, eventmap={
                iPlayableService.evTunedIn: self.tuned,
            })

        self.retValue = True
        self.provider_index = 0
        self.status = 0
        self.open = False
        self.saved = False
        self.tune_enabled = False
        self.oldService = self.session.nav.getCurrentlyPlayingServiceReference(
        )
        self.config = CrossEPG_Config()
        self.config.load()
        self.providers = providers
        self.pcallback = pcallback

        self.wrapper = CrossEPG_Wrapper()
        self.wrapper.addCallback(self.wrapperCallback)

        self.timeout = eTimer()
        self.timeout.callback.append(self.quit)

        self.hideprogress = eTimer()
        self.hideprogress.callback.append(self["progress"].hide)

        self.pcallbacktimer = eTimer()
        self.pcallbacktimer.callback.append(self.doCallback)

        self.wrappertimer = eTimer()
        self.wrappertimer.callback.append(self.initWrapper)

        if noosd:
            self.wrappertimer.start(100, 1)
        else:
            self.onFirstExecBegin.append(self.firstExec)
Esempio n. 50
0
	def __init__(self, session, args = None):
		Screen.__init__(self, session)
		InfoBarAudioSelection.__init__(self)
		InfoBarCueSheetSupport.__init__(self, actionmap = "MediaPlayerCueSheetActions")
		InfoBarNotifications.__init__(self)
		InfoBarBase.__init__(self)
		InfoBarScreenSaver.__init__(self)
		InfoBarSubtitleSupport.__init__(self)
		HelpableScreen.__init__(self)
		self.summary = None
		self.oldService = self.session.nav.getCurrentlyPlayingServiceOrGroup()
		self.session.nav.stopService()

		self.setTitle(_("Media player"))

		self.playlistparsers = {}
		self.addPlaylistParser(PlaylistIOM3U, "m3u")
		self.addPlaylistParser(PlaylistIOPLS, "pls")
		self.addPlaylistParser(PlaylistIOInternal, "e2pls")

		# 'None' is magic to start at the list of mountpoints
		defaultDir = config.mediaplayer.defaultDir.getValue()
		self.filelist = FileList(defaultDir, matchingPattern = "(?i)^.*\.(dts|mp3|wav|wave|oga|ogg|flac|m4a|mp2|m2a|wma|ac3|mka|aac|ape|alac|mpg|vob|m4v|mkv|avi|divx|dat|flv|mp4|mov|wmv|asf|3gp|3g2|mpeg|mpe|rm|rmvb|ogm|ogv|m2ts|mts|ts|m3u|e2pls|pls)", useServiceRef = True, additionalExtensions = "4098:m3u 4098:e2pls 4098:pls")
		self["filelist"] = self.filelist

		self.playlist = MyPlayList()
		self.is_closing = False
		self.delname = ""
		self.playlistname = ""
		self["playlist"] = self.playlist

		self["PositionGauge"] = ServicePositionGauge(self.session.nav)

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

		self["artisttext"] = Label(_("Artist")+':')
		self["artist"] = Label("")
		self["titletext"] = Label(_("Title")+':')
		self["title"] = Label("")
		self["albumtext"] = Label(_("Album")+':')
		self["album"] = Label("")
		self["yeartext"] = Label(_("Year")+':')
		self["year"] = Label("")
		self["genretext"] = Label(_("Genre")+':')
		self["genre"] = Label("")
		self["coverArt"] = MediaPixmap()
		self["repeat"] = MultiPixmap()

		self.seek_target = None

		try:
			from Plugins.SystemPlugins.Hotplug.plugin import hotplugNotifier
			hotplugNotifier.append(self.hotplugCB)
		except Exception, ex:
			print "[MediaPlayer] No hotplug support", ex
Esempio n. 51
0
    def __init__(self,
                 session,
                 title="",
                 list=None,
                 keys=None,
                 selection=0,
                 skin_name=None,
                 text="",
                 reorderConfig="",
                 var="",
                 windowTitle=None,
                 allow_cancel=True,
                 titlebartext=_("Choice Box")):
        if not windowTitle:  #for compatibility
            windowTitle = titlebartext
        if not list: list = []
        if not skin_name: skin_name = []
        Screen.__init__(self, session)

        self.allow_cancel = allow_cancel

        if isinstance(skin_name, str):
            skin_name = [skin_name]
        self.skinName = skin_name + ["ChoiceBox"]

        self.reorderConfig = reorderConfig
        self["text"] = Label()
        self.var = ""
        if skin_name and 'SoftwareUpdateChoices' in skin_name and var and var in (
                'unstable', 'updating', 'stable', 'unknown'):
            self.var = var
            self['feedStatusMSG'] = Label()
            self['tl_off'] = Pixmap()
            self['tl_red'] = Pixmap()
            self['tl_yellow'] = Pixmap()
            self['tl_green'] = Pixmap()

        title_max = 55
        if 'MetrixHD/' in config.skin.primary_skin.value:
            title_max += 10
        if title:
            title = _(title)
            if len(title) < title_max and title.find('\n') == -1:
                Screen.setTitle(self, title)
            elif title.find('\n') != -1:
                temptext = title.split('\n')
                if len(temptext[0]) < title_max:
                    Screen.setTitle(self, temptext[0])
                    count = 2
                    labeltext = ""
                    while len(temptext) >= count:
                        if labeltext:
                            labeltext += '\n'
                        labeltext = labeltext + temptext[count - 1]
                        count += 1
                        print '[Choicebox] count', count
                    self["text"].setText(labeltext)
                else:
                    self["text"] = Label(title)
            else:
                self["text"] = Label(title)
        elif text:
            self["text"] = Label(_(text))
        self.list = []
        self.summarylist = []
        if keys is None:
            self.__keys = [
                "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "red",
                "green", "yellow", "blue", "text"
            ] + (len(list) - 14) * [""]
        else:
            self.__keys = keys + (len(list) - len(keys)) * [""]

        self.keymap = {}
        pos = 0
        if self.reorderConfig:
            self.config_type = eval("config.misc.pluginlist." +
                                    self.reorderConfig)
            if self.config_type.value:
                prev_list = zip(list, self.__keys)
                new_list = []
                for x in self.config_type.value.split(","):
                    for entry in prev_list:
                        if entry[0][0] == x:
                            new_list.append(entry)
                            prev_list.remove(entry)
                list = zip(*(new_list + prev_list))
                list, self.__keys = list[0], list[1]
                number = 1
                new_keys = []
                for x in self.__keys:
                    if (not x or x.isdigit()) and number <= 10:
                        new_keys.append(str(number % 10))
                        number += 1
                    else:
                        new_keys.append(not x.isdigit() and x or "")
                self.__keys = new_keys
        for x in list:
            strpos = str(self.__keys[pos])
            self.list.append(ChoiceEntryComponent(key=strpos, text=x))
            if self.__keys[pos] != "":
                self.keymap[self.__keys[pos]] = list[pos]
            self.summarylist.append((self.__keys[pos], x[0]))
            pos += 1
        self["windowtitle"] = Label(_(windowTitle))
        self["list"] = ChoiceList(list=self.list, selection=selection)
        self["summary_list"] = StaticText()
        self["summary_selection"] = StaticText()
        self.updateSummary(selection)

        self["actions"] = NumberActionMap(
            [
                "WizardActions", "InputActions", "ColorActions",
                "DirectionActions", "MenuActions"
            ],
            {
                "ok": self.go,
                "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,
                "red": self.keyRed,
                "green": self.keyGreen,
                "yellow": self.keyYellow,
                "blue": self.keyBlue,
                "text": self.keyText,
                "up": self.up,
                "down": self.down,
                "left": self.left,
                "right": self.right,
                "moveUp": self.additionalMoveUp,
                "moveDown": self.additionalMoveDown,
                "menu": self.setDefaultChoiceList,
                "back": lambda: 0,  # drop through to self["cancelaction"]
            },
            prio=-2)

        self["cancelaction"] = ActionMap(["WizardActions"], {
            "back": self.cancel,
        },
                                         prio=-1)
        self.onShown.append(self.onshow)
Esempio n. 52
0
	def __init__(self, session, parent):
		Screen.__init__(self, session)
		self["text1"] = Label("Media player")
		self["text3"] = Label("")
		self["text4"] = Label("")
Esempio n. 53
0
    def __init__(self,
                 session,
                 text="",
                 filename="",
                 currDir=None,
                 bookmarks=None,
                 userMode=False,
                 windowTitle=None,
                 minFree=None,
                 autoAdd=False,
                 editDir=False,
                 inhibitDirs=[],
                 inhibitMounts=[]):
        # Init parents
        Screen.__init__(self, session)
        NumericalTextInput.__init__(self, handleTimeout=False)
        HelpableScreen.__init__(self)

        # Set useable chars
        self.setUseableChars(u'1234567890abcdefghijklmnopqrstuvwxyz')

        # Quickselect Timer
        self.qs_timer = eTimer()
        self.qs_timer.callback.append(self.timeout)
        self.qs_timer_type = 0

        # Initialize Quickselect
        self.curr_pos = -1
        self.quickselect = ""

        # Set Text
        self["text"] = Label(text)
        self["textbook"] = Label(_("Bookmarks"))

        # Save parameters locally
        self.text = text
        self.filename = filename
        self.minFree = minFree
        self.realBookmarks = bookmarks
        self.bookmarks = bookmarks and bookmarks.value[:] or []
        self.userMode = userMode
        self.autoAdd = autoAdd
        self.editDir = editDir
        self.inhibitDirs = inhibitDirs

        # Initialize FileList
        self["filelist"] = FileList(currDir,
                                    showDirectories=True,
                                    showFiles=False,
                                    inhibitMounts=inhibitMounts,
                                    inhibitDirs=inhibitDirs)

        # Initialize BookList
        self["booklist"] = MenuList(self.bookmarks)

        # Buttons
        self["key_green"] = Button(_("OK"))
        self["key_yellow"] = Button(_("Rename"))
        self["key_blue"] = Button(_("Remove bookmark"))
        self["key_red"] = Button(_("Cancel"))

        # Background for Buttons
        self["green"] = Pixmap()
        self["yellow"] = Pixmap()
        self["blue"] = Pixmap()
        self["red"] = Pixmap()

        # Initialize Target
        self["target"] = Label()

        if self.userMode:
            self.usermodeOn()

        # Custom Action Handler
        class LocationBoxActionMap(HelpableActionMap):
            def __init__(self, parent, context, actions={}, prio=0):
                HelpableActionMap.__init__(self, parent, context, actions,
                                           prio)
                self.box = parent

            def action(self, contexts, action):
                # Reset Quickselect
                self.box.timeout(force=True)

                return HelpableActionMap.action(self, contexts, action)

        # Actions that will reset quickselect
        self["WizardActions"] = LocationBoxActionMap(
            self, "WizardActions", {
                "left": self.left,
                "right": self.right,
                "up": self.up,
                "down": self.down,
                "ok": (self.ok, _("select")),
                "back": (self.cancel, _("Cancel")),
            }, -2)

        self["ColorActions"] = LocationBoxActionMap(
            self, "ColorActions", {
                "red": self.cancel,
                "green": self.select,
                "yellow": self.changeName,
                "blue": self.addRemoveBookmark,
            }, -2)

        self["EPGSelectActions"] = LocationBoxActionMap(
            self, "EPGSelectActions", {
                "prevBouquet":
                (self.switchToBookList, _("switch to bookmarks")),
                "nextBouquet":
                (self.switchToFileList, _("switch to filelist")),
            }, -2)

        self["MenuActions"] = LocationBoxActionMap(self, "MenuActions", {
            "menu": (self.showMenu, _("menu")),
        }, -2)

        # Actions used by quickselect
        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
            })

        # Run some functions when shown
        if windowTitle is None:
            windowTitle = _("Select location")
        self.onShown.extend((
            boundFunction(self.setTitle, windowTitle),
            self.updateTarget,
            self.showHideRename,
        ))

        self.onLayoutFinish.append(self.switchToFileListOnStart)

        # Make sure we remove our callback
        self.onClose.append(self.disableTimer)
Esempio n. 54
0
	def __init__(self, session, args = None):

		self.session = session
		path = "/usr/lib/enigma2/python/Plugins/Extensions/IPTV-List-Updater/skins/original/Start.xml"
		print path
		with open(path, "r") as f:
			self.skin = f.read()
			f.close()
		
		Screen.__init__(self, session)
		
		self["title"] = Label(_("Version %s" % Version))
		self["maintain"] = Label(_("(c) by Nobody28 & satinfo"))
		self["link1"] = Label(_("www.opena.tv"))
		self["link2"] = Label(_("www.gigablue-support.com"))
		self["description"] = Label(_("Install & update IPTV streams from country list"))
		self["description2"] = Label(_("and add into TV Bouquet or Radio Bouquet"))
		self["thanks"] = Label(_("Special thanks goes to HasBahCa & FreeTuxTV for the links"))
		
		self["actions"] = ActionMap(["OkCancelActions", "WizardActions", "ColorActions", "SetupActions", "NumberActions", "EPGSelectActions"],
		{
			"ok": self.go,
			"back": self.close,
			"red": self.close,
			"green": self.go,
			"yellow": self.change,
			"blue": self.credits,
			"info": self.faq,
			"menu": self.mod,
		}, -1)
		self["key_red"] = Label(_("Close"))
		self["key_green"] = Label(_("Start"))
		self["key_yellow"] = Label(_("Changelog"))
		self["key_blue"] = Label(_("Credits"))
Esempio n. 55
0
    def __init__(self,
                 session,
                 showSteps=True,
                 showStepSlider=True,
                 showList=True,
                 showConfig=True):
        Screen.__init__(self, session)

        self.isLastWizard = False  # can be used to skip a "goodbye"-screen in a wizard

        self.stepHistory = []

        self.wizard = {}
        parser = make_parser()
        if not isinstance(self.xmlfile, list):
            self.xmlfile = [self.xmlfile]
# 		print "Reading ", self.xmlfile
        wizardHandler = self.parseWizard(self.wizard)
        parser.setContentHandler(wizardHandler)
        for xmlfile in self.xmlfile:
            if xmlfile[0] != '/':
                parser.parse(eEnv.resolve('${datadir}/enigma2/') + xmlfile)
            else:
                parser.parse(xmlfile)

        self.showSteps = showSteps
        self.showStepSlider = showStepSlider
        self.showList = showList
        self.showConfig = showConfig

        self.numSteps = len(self.wizard)
        self.currStep = self.getStepWithID("start") + 1

        self.timeoutTimer = eTimer()
        self.timeoutTimer.callback.append(self.timeoutCounterFired)

        self["text"] = Label()

        if showConfig:
            self["config"] = ConfigList([], session=session)

        if self.showSteps:
            self["step"] = Label()

        if self.showStepSlider:
            self["stepslider"] = Slider(1, self.numSteps)

        if self.showList:
            self.list = []
            self["list"] = List(self.list, enableWrapAround=True)
            self["list"].onSelectionChanged.append(self.selChanged)
            #self["list"] = MenuList(self.list, enableWrapAround = True)

        self.onShown.append(self.updateValues)

        self.configInstance = None
        self.currentConfigIndex = None

        Wizard.instance = self

        self.lcdCallbacks = []
        self.first = False

        self.disableKeys = False

        self["actions"] = NumberActionMap(
            [
                "WizardActions", "DirectionActions", "NumberActions",
                "ColorActions", "SetupActions", "InputAsciiActions",
                "KeyboardInputActions"
            ], {
                "gotAsciiCode": self.keyGotAscii,
                "ok": self.ok,
                "back": self.back,
                "left": self.left,
                "right": self.right,
                "up": self.up,
                "down": self.down,
                "red": self.red,
                "green": self.green,
                "yellow": self.yellow,
                "blue": self.blue,
                "deleteBackward": self.deleteBackward,
                "deleteForward": self.deleteForward,
                "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
            }, -1)

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

        self["VirtualKB"].setEnabled(False)
Esempio n. 56
0
	def __init__(self, session):
		Screen.__init__(self, session)
		if config.usage.show_infobar_lite.value and (config.skin.primary_skin.value == "DMConcinnity-HD/skin.xml" or config.skin.primary_skin.value.startswith('MetrixHD/')):
			self.skinName = "InfoBarLite"

		self["actions"] = HelpableActionMap(self, "InfobarActions",
			{
				"showMovies": (self.showMovies, _("Play recorded movies...")),
				"showRadio": (self.showRadioButton, _("Show the radio player...")),
				"showTv": (self.showTvButton, _("Show the tv player...")),
				"toogleTvRadio": (self.toogleTvRadio, _("Toggels between tv and radio...")),
				"openBouquetList": (self.openBouquetList, _("Open bouquetlist...")),
				"showMediaPlayer": (self.showMediaPlayer, _("Show the media player...")),
				"openTimerList": (self.openTimerList, _("Open Timerlist...")),
				"openAutoTimerList": (self.openAutoTimerList, _("Open AutoTimerlist...")),
				"openEPGSearch": (self.openEPGSearch, _("Open EPGSearch...")),
				"openIMDB": (self.openIMDB, _("Open IMDB...")),
				"showMC": (self.showMediaCenter, _("Show the media center...")),
				"openSleepTimer": (self.openSleepTimer, _("Show the Sleep Timer...")),
				"openPowerTimerList": (self.openPowerTimerList, _("Show the Power Timer...")),
				'ZoomInOut': (self.ZoomInOut, _('Zoom In/Out TV...')),
				'ZoomOff': (self.ZoomOff, _('Zoom Off...')),
				'HarddiskSetup': (self.HarddiskSetup, _('Select HDD')),	
				"showWWW": (self.showPORTAL, _("Open MediaPortal...")),
				"showSetup": (self.showSetup, _("Show setup...")),
				"showInformation": (self.showInformation, _("Show Information...")),
				"showFormat": (self.showFormat, _("Show Format Setup...")),
				"showPluginBrowser": (self.showPluginBrowser, _("Show the plugins...")),
				"showBoxPortal": (self.showBoxPortal, _("Show Box Portal...")),
				"openSimpleUnmount": (self.openSimpleUnmount, _("Simple umounter mass storage device.")),
			}, prio=2)

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

		self.allowPiP = True
		self.radioTV = 0

		for x in HelpableScreen, \
				InfoBarBase, InfoBarShowHide, \
				InfoBarNumberZap, InfoBarChannelSelection, InfoBarMenu, InfoBarEPG, InfoBarRdsDecoder, \
				InfoBarInstantRecord, InfoBarAudioSelection, InfoBarRedButton, InfoBarTimerButton, InfoBarUnhandledKey, InfoBarLongKeyDetection, InfoBarINFOpanel, InfoBarResolutionSelection, InfoBarVmodeButton, \
				InfoBarAdditionalInfo, InfoBarNotifications, InfoBarDish, InfoBarSubserviceSelection, InfoBarAspectSelection, InfoBarBuffer, \
				InfoBarTimeshift, InfoBarSeek, InfoBarCueSheetSupport, InfoBarSummarySupport, InfoBarTimeshiftState, \
				InfoBarTeletextPlugin, InfoBarExtensions, InfoBarPiP, InfoBarSubtitleSupport, InfoBarJobman, InfoBarZoom, InfoBarSleepTimer, InfoBarOpenOnTopHelper, InfoBarHandleBsod, \
				InfoBarHdmi, InfoBarPlugins, InfoBarServiceErrorPopupSupport, InfoBarButtonSetup:
			x.__init__(self)

		self.helpList.append((self["actions"], "InfobarActions", [("showMovies", _("Watch recordings..."))]))
		self.helpList.append((self["actions"], "InfobarActions", [("showRadio", _("Listen to the radio..."))]))

		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				enigma.iPlayableService.evUpdatedEventInfo: self.__eventInfoChanged
			})

		self.current_begin_time=0
		assert InfoBar.instance is None, "class InfoBar is a singleton class and just one instance of this class is allowed!"
		InfoBar.instance = self

		if config.misc.initialchannelselection.value:
			self.onShown.append(self.showMenu)

		self.zoomrate = 0
		self.zoomin = 1

		self.onShow.append(self.doButtonsCheck)
Esempio n. 57
0
    def __init__(self, session, archivCZSK):
        provider = ArchivCZSKContentProvider(archivCZSK, os.path.join(settings.PLUGIN_PATH, 'categories'))
        provider.start()
        contentHandler = ArchivCZSKContentHandler(session, self, provider)
        defaultCategory = config.plugins.archivCZSK.defaultCategory.value
        categoryItem = categoryAddons = None
        if defaultCategory != 'categories':
            categoryItem = provider.get_content({'category':defaultCategory})
            categoryAddons = provider.get_content({'category_addons':defaultCategory})
            # dont add PExit() if default category is user created cat.
            gotParrent = True
            try:
                gotParrent = self.getParent() is not None
            except:
                pass
            if gotParrent and (defaultCategory=='all_addons' or defaultCategory=='tv_addons' or defaultCategory=='video_addons'):
                categoryAddons is not None and categoryAddons.insert(0, PExit())
        categoryItems = provider.get_content()
        BaseContentScreen.__init__(self, session, contentHandler, categoryItems)
        if categoryItem is not None  and categoryAddons is not None:
            self.save()
            self.load({'lst_items':categoryAddons,
                            'parent_it':categoryItem,
                            'refresh':False})
        self.ctx_items.append((_("Add Category"), None, self.addCategory))
        self.provider = provider
        self.updateGUITimer = eTimer()
        self.updateGUITimer_conn = eConnectCallback(self.updateGUITimer.timeout, self.updateAddonGUI)

        # include DownloadList
        DownloadList.__init__(self)

        # include TipList
        TipBar.__init__(self, [self.CONTEXT_TIP], startOnShown=True)
        self.onUpdateGUI.append(self.changeAddon)
        self.onClose.append(self.__onClose)

        from Plugins.Extensions.archivCZSK.version import version
        self.setTitle("ArchivCZSK ("+toString(version)+")")
        self["image"] = Pixmap()
        self["title"] = Label("")
        self["author"] = Label("")
        self["version"] = Label("")
        self["about"] = Label("")

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

        self["actions"] = ActionMap(["archivCZSKActions"],
            {
                "ok": self.ok,
                "cancel": self.cancel,
                "up": self.up,
                "down": self.down,
                "blue": self.openSettings,
                "red": self.openAddonManagement,
                "menu" : self.menu
            }, -2)
        # after layout show update item "GUI" - edit: shamann
        self.onLayoutFinish.append(self.updateAddonGUI)
Esempio n. 58
0
    def __init__(self, session, showExtentionMenuOption):
        Screen.__init__(self, session)

        self.setup_title = _("Softcam setup")

        self["actions"] = ActionMap(
            ["OkCancelActions", "ColorActions", "CiSelectionActions"], {
                "cancel": self.cancel,
                "green": self.save,
                "red": self.cancel,
                "blue": self.ppanelShortcut,
            }, -1)

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

        self.softcam = CamControl('softcam')
        self.cardserver = CamControl('cardserver')

        self.ecminfo = GetEcmInfo()
        (newEcmFound, ecmInfo) = self.ecminfo.getEcm()
        self["info"] = ScrollLabel("".join(ecmInfo))
        self.EcmInfoPollTimer = eTimer()
        self.EcmInfoPollTimer.callback.append(self.setEcmInfo)
        self.EcmInfoPollTimer.start(1000)

        softcams = self.softcam.getList()
        cardservers = self.cardserver.getList()

        self.softcams = ConfigSelection(choices=softcams)
        self.softcams.value = self.softcam.current()

        self.list.append(getConfigListEntry(_("Select Softcam"),
                                            self.softcams))
        if cardservers:
            self.cardservers = ConfigSelection(choices=cardservers)
            self.cardservers.value = self.cardserver.current()
            self.list.append(
                getConfigListEntry(_("Select Card Server"), self.cardservers))

        self.list.append(
            getConfigListEntry(_("Restart softcam"),
                               ConfigAction(self.restart, "s")))
        if cardservers:
            self.list.append(
                getConfigListEntry(_("Restart cardserver"),
                                   ConfigAction(self.restart, "c")))
            self.list.append(
                getConfigListEntry(_("Restart both"),
                                   ConfigAction(self.restart, "sc")))

        if showExtentionMenuOption:
            self.list.append(
                getConfigListEntry(_("Show softcam setup in extensions menu"),
                                   config.misc.softcam_setup.extension_menu))

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

        self.onLayoutFinish.append(self.layoutFinished)
Esempio n. 59
0
	def __init__(self, session, feid):
		self.skin = PositionerSetup.skin
		Screen.__init__(self, session)
		self.feid = feid
		self.oldref = None

		cur = { }
		if not self.openFrontend():
			self.oldref = session.nav.getCurrentlyPlayingServiceReference()
			service = session.nav.getCurrentService()
			feInfo = service and service.frontendInfo()
			if feInfo:
				cur = feInfo.getTransponderData(True)
			del feInfo
			del service
			session.nav.stopService() # try to disable foreground service
			if not self.openFrontend():
				if session.pipshown: # try to disable pip
					service = self.session.pip.pipservice
					feInfo = service and service.frontendInfo()
					if feInfo:
						cur = feInfo.getTransponderData()
					del feInfo
					del service
					session.pipshown = False
					session.deleteDialog(session.pip)
					del session.pip
					if not self.openFrontend():
						self.frontend = None # in normal case this should not happen

		self.frontendStatus = { }
		self.diseqc = Diseqc(self.frontend)
		self.tuner = Tuner(self.frontend, True) #True means we dont like that the normal sec stuff sends commands to the rotor!

		tp = ( cur.get("frequency", 0) / 1000,
			cur.get("symbol_rate", 0) / 1000,
			cur.get("polarization", eDVBFrontendParametersSatellite.Polarisation_Horizontal),
			cur.get("fec_inner", eDVBFrontendParametersSatellite.FEC_Auto),
			cur.get("inversion", eDVBFrontendParametersSatellite.Inversion_Unknown),
			cur.get("orbital_position", 0),
			cur.get("system", eDVBFrontendParametersSatellite.System_DVB_S),
			cur.get("modulation", eDVBFrontendParametersSatellite.Modulation_QPSK),
			cur.get("rolloff", eDVBFrontendParametersSatellite.RollOff_alpha_0_35),
			cur.get("pilot", eDVBFrontendParametersSatellite.Pilot_Unknown))

		self.tuner.tune(tp)
		self.createConfig()

		self.isMoving = False
		self.stopOnLock = False

		self.red = Label("")
		self["red"] = self.red
		self.green = Label("")
		self["green"] = self.green
		self.yellow = Label("")
		self["yellow"] = self.yellow
		self.blue = Label("")
		self["blue"] = self.blue

		self.list = []
		self["list"] = ConfigList(self.list)
		self.createSetup()

		self["snr_db"] = TunerInfo(TunerInfo.SNR_DB, statusDict = self.frontendStatus)
		self["snr_percentage"] = TunerInfo(TunerInfo.SNR_PERCENTAGE, statusDict = self.frontendStatus)
		self["ber_value"] = TunerInfo(TunerInfo.BER_VALUE, statusDict = self.frontendStatus)
		self["snr_bar"] = TunerInfo(TunerInfo.SNR_BAR, statusDict = self.frontendStatus)
		self["ber_bar"] = TunerInfo(TunerInfo.BER_BAR, statusDict = self.frontendStatus)
		self["lock_state"] = TunerInfo(TunerInfo.LOCK_STATE, statusDict = self.frontendStatus)

		self["frequency_value"] = Label("")
		self["symbolrate_value"] = Label("")
		self["fec_value"] = Label("")

		self["actions"] = ActionMap(["DirectionActions", "OkCancelActions", "ColorActions"],
		{
			"ok": self.go,
			"cancel": self.keyCancel,
			"up": self.up,
			"down": self.down,
			"left": self.left,
			"right": self.right,
			"red": self.redKey,
			"green": self.greenKey,
			"yellow": self.yellowKey,
			"blue": self.blueKey,
		}, -1)

		self.updateColors("tune")

		self.statusTimer = eTimer()
		self.statusTimer_conn = self.statusTimer.timeout.connect(self.updateStatus)
		self.statusTimer.start(50, True)
		self.onClose.append(self.__onClose)
Esempio n. 60
0
 def __init__(self, session, service, eventName=None, shortDescription=None):
     Screen.__init__(self, session)
     InfoLoadChoice.__init__(self, self.callback_green_pressed)
     self.skinName = SkinTools.appendResolution('TheTVDBMain')
     if not pathExists(temp_dir):
         os.mkdir(temp_dir, 511)
     self['setupActions'] = ActionMap(['ColorActions', 'DirectionActions', 'SetupActions', 'OkCancelActions'], {'exit': self.cancel, 
        'ok': self.ok_pressed, 
        'red': self.red_pressed, 
        'green': self.green_pressed, 
        'blue': self.blue_pressed, 
        'yellow': self.yellow_pressed, 
        'cancel': self.cancel, 
        'upUp': self.pageUp, 
        'leftUp': self.pageUp, 
        'downUp': self.pageDown, 
        'rightUp': self.pageDown})
     self.service = service
     self.ratingstars = -1
     self.searchTitle = eventName
     self.description = shortDescription
     if service is not None:
         info = ServiceCenter.getInstance().info(service)
         self.searchTitle = info.getName(service)
         self.description = info.getInfoString(service, iServiceInformation.sDescription)
     print('[tvdb]', str(self.searchTitle), '-', str(self.description))
     if self.description == self.searchTitle:
         self.description = ''
     self.picload = ePicLoad()
     self.picload.PictureData.get().append(self.paintPosterPixmapCB)
     self.picload2 = ePicLoad()
     self.picload2.PictureData.get().append(self.paintBannerPixmapCB)
     self['cover'] = Pixmap()
     self['banner'] = Pixmap()
     self['stars'] = ProgressBar()
     self['no_stars'] = Pixmap()
     self['description'] = ScrollLabel('')
     self['description_episode'] = ScrollLabel('')
     self['extended'] = Label('')
     self['extended_episode'] = Label('')
     self['status'] = Label('')
     self['result_txt'] = Label('')
     self['voted'] = Label('')
     self['list'] = SeriesList()
     self['episodes_list'] = EpisodesList()
     self['seperator'] = Pixmap()
     self['thetvdb_logo'] = Pixmap()
     self['button_red'] = Pixmap()
     self['button_green'] = Pixmap()
     self['button_yellow'] = Pixmap()
     self['button_blue'] = Pixmap()
     self['key_red'] = StaticText('')
     self['key_green'] = StaticText('')
     self['key_yellow'] = StaticText('')
     self['key_blue'] = StaticText('')
     self.timer = eTimer()
     self.timer.callback.append(self.getSeriesList)
     self.red_button_timer = eTimer()
     self.red_button_timer.callback.append(self.callback_red_pressed)
     self.blue_button_timer = eTimer()
     self.blue_button_timer.callback.append(self.callback_blue_pressed)
     self.onLayoutFinish.append(self.layoutFinished)
     self.onClose.append(self.deleteTempDir)
     self.view_mode = self.SHOW_SEARCH
     self.updateView()
     self.startSearch()
     return