def setText(self, text): text = (self.displayLength * ' ') + text self.longText = text self.offset = 0 text = text[:self.displayLength] if PY2: text = text.encode('utf-8', 'ignore') Label.setText(self, text)
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)
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 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()
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)
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" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/blue.png" position="210,5" size="200,40" alphatest="on" /> <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" 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" 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>""" BASIC_SETTINGS = [ config.streamserver.user, config.streamserver.password, config.streamserver.source, config.streamserver.resolution, config.streamserver.framerate, config.streamserver.profile, config.streamserver.slices, config.streamserver.level, ] 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.__encoderRestartRequired = False 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) config.streamserver.rtsp.enabled.addNotifier(self._onEnabled, initial_call=False) config.streamserver.hls.enabled.addNotifier(self._onEnabled, initial_call=False) config.streamserver.gopLength.addNotifier(self._onGopLengthChanged, initial_call=False) config.streamserver.bFrames.addNotifier(self._onBframesChanged, initial_call=False) #Basic encoder setting change notifier for cfg in self.BASIC_SETTINGS: cfg.addNotifier(self._onBasicEncoderSettingChanged, initial_call=False) self._createSetup() def _onBframesChanged(self, element): self._createSetup() def _getEncoderRestartRequired(self): return self.__encoderRestartRequired def _setEncoderRestartRequired(self, value): self.__encoderRestartRequired = value if self.__encoderRestartRequired: self._key_blue.setText(_("Apply")) else: self._key_blue.setText("") _encoderRestartRequired = property(_getEncoderRestartRequired, _setEncoderRestartRequired) 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): if self._encoderRestartRequired: self.session.openWithCallback( self._onEncoderRestartResponse, MessageBox, text= _("You have changed basic encoder settings.\nTo apply these changes all streams have to be stopped.\nDo you want to stop and restart all streams now to apply these settings immediately?" ), title=_("Stream restart required")) return else: applyConfig(self._streamServerControl) if self._closeAfterApply: self.close() def _onEncoderRestartResponse(self, response): self._encoderRestartRequired = False if response: applyConfig(self._streamServerControl, forceRestart=True) else: applyConfig(self._streamServerControl) if self._closeAfterApply: self.close() def _applyAndClose(self): self._closeAfterApply = True self.apply() def close(self): streamServerControl.onRtspClientCountChanged.remove( self._onRtspClientCountChanged) config.streamserver.rtsp.enabled.removeNotifier(self._onEnabled) config.streamserver.hls.enabled.removeNotifier(self._onEnabled) for cfg in self.BASIC_SETTINGS: cfg.removeNotifier(self._onBasicEncoderSettingChanged) config.streamserver.gopLength.removeNotifier(self._onGopLengthChanged) config.streamserver.bFrames.removeNotifier(self._onBframesChanged) config.streamserver.save() Screen.close(self) def _onEnabled(self, element): if not self._streamServerControl.isConnected(): return self.apply() config.streamserver.save() self._createSetup() def _onGopLengthChanged(self, element): self._createSetup() def _onMediatorEnabled(self, element): if not self._streamServerControl.isConnected(): return self._createSetup() def _onBasicEncoderSettingChanged(self, element): self._encoderRestartRequired = True def _createSetup(self): self._setInfoText() if not self._streamServerControl.isConnected(): return entries = [ getConfigListEntry(_("RTSP")), getConfigListEntry(_("RTSP Server"), config.streamserver.rtsp.enabled), ] if config.streamserver.rtsp.enabled.value: entries.extend([ getConfigListEntry(_("User"), config.streamserver.user), getConfigListEntry(_("Password"), config.streamserver.password), ]) if config.usage.setup_level.index > 0: entries.extend([ getConfigListEntry(_("RTSP Port"), config.streamserver.rtsp.port), getConfigListEntry(_("RTSP Path"), config.streamserver.rtsp.path), ]) entries.extend([ getConfigListEntry(_("HLS")), getConfigListEntry(_("HLS Server"), config.streamserver.hls.enabled) ]) if config.streamserver.hls.enabled.value and config.usage.setup_level.index > 0: entries.append( getConfigListEntry(_("HLS Port"), config.streamserver.hls.port)) if config.streamserver.rtsp.enabled.value: entries.append(getConfigListEntry(_("Authentication"))) if self._streamServerControl.isAnyEnabled(): entries.extend([ getConfigListEntry(_("Bitrates")), getConfigListEntry(_("Audio Bitrate"), config.streamserver.audioBitrate), getConfigListEntry(_("Video Bitrate"), config.streamserver.videoBitrate), getConfigListEntry(_("Basic Encoder Settings")), getConfigListEntry(_("Data Source"), config.streamserver.source), getConfigListEntry(_("Resolution"), config.streamserver.resolution), getConfigListEntry(_("Framerate"), config.streamserver.framerate), getConfigListEntry(_("Expert Encoder Settings")), getConfigListEntry( _("GOP Length (ms, P-Frames auto calculated)"), config.streamserver.gopLength) ]) if config.streamserver.gopLength.value == eStreamServer.GOP_LENGTH_AUTO: entries.append( getConfigListEntry(_("Number of P-Frames"), config.streamserver.pFrames)) entries.append( getConfigListEntry(_("Number of B-Frames"), config.streamserver.bFrames)) if config.streamserver.bFrames.value: entries.append( getConfigListEntry(_("Open GOP"), config.streamserver.openGop)) if StreamServerControl.FEATURE_SCENE_DETECTION and not config.streamserver.bFrames.value and not config.streamserver.gopLength.value: entries.append( getConfigListEntry(_("New GOP On Scene Change"), config.streamserver.gopOnSceneChange)) if StreamServerControl.FEATURE_SLICES: entries.append( getConfigListEntry(_("Number of slices"), config.streamserver.slices)) entries.extend([ getConfigListEntry(_("Level"), config.streamserver.level), getConfigListEntry(_("Profile"), config.streamserver.profile), ]) self["config"].list = entries def _setInfoText(self): if not self._streamServerControl.isConnected(): self._info.setText(_("ERROR: Streaming Server not available!")) return detailtext = _("Local client(s):\n %s") % (self._clientCount) self._details.setText(detailtext) localstreams = [] if config.streamserver.rtsp.enabled.value or 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 config.streamserver.rtsp.enabled.value: localstreams.append( "rtsp://%s:%s/%s" % (ip.getAddress(), config.streamserver.rtsp.port.value, config.streamserver.rtsp.path.value)) if config.streamserver.hls.enabled.value: localstreams.append( "http://%s:%s/dream.m3u8" % (ip.getAddress(), config.streamserver.hls.port.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] config.streamserver.videoBitrate.value = preset.videoBitrate config.streamserver.audioBitrate.value = preset.audioBitrate if preset.resolution != config.streamserver.resolution.value: config.streamserver.resolution.value = preset.resolution self._createSetup()
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()
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 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) 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.callback.append(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.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)
class SetupGuide(Screen): MENU_CHOICE_LEAVE = "leave" skin = """<screen name="SetupGuide" position="0,0" size="1280,720" title="Welcome" flags="wfNoBorder"> <widget name="banner" position="0,0" size="240,720" pixmap="skin_default/wizard.png" scale="fill" /> <widget source="green" render="Pixmap" pixmap="skin_default/buttons/green.png" position="475,15" size="200,40" > <convert type="ConditionalShowHide"/> </widget> <widget name="green_text" position="475,15" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-2,-2"/> <widget source="yellow" render="Pixmap" pixmap="skin_default/buttons/yellow.png" position="685,15" size="200,40" > <convert type="ConditionalShowHide"/> </widget> <widget name="yellow_text" position="685,15" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-2,-2"/> <widget source="blue" render="Pixmap" pixmap="skin_default/buttons/blue.png" position="895,15" size="200,40" > <convert type="ConditionalShowHide"/> </widget> <widget name="blue_text" position="895,15" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-2,-2"/> <widget source="Title" render="Label" position="250,70" size="950,40" font="Regular;36" halign="center" valign="center" /> <widget name="text" position="250,120" size="950,240" font="Regular;24" halign="center" valign="center" /> <widget source="list" render="Listbox" position="250,370" size="950,300" zPosition="1" enableWrapAround="1" scrollbarMode="showOnDemand" transparent="1"> <convert type="TemplatedMultiContent"> {"templates": { "default" : (28,[ MultiContentEntryText(pos=(10,4),size=(580,22),flags=RT_HALIGN_LEFT,text=0) ]), "iconized" : (50,[ MultiContentEntryText(pos=(75,0),size=(310,50),flags=RT_HALIGN_LEFT|RT_VALIGN_CENTER,text=0),# index 0 is the text, MultiContentEntryPixmap(pos=(5,5),size=(60,40),png=1),# index 1 is the pixmap ]), "networkservice" : (50,[ MultiContentEntryPixmapAlphaTest(pos=(0,0),size=(50,50),png=1),#type icon MultiContentEntryText(pos=(55,0),size=(400,24),font=0,flags=RT_HALIGN_LEFT,text=3),#service name MultiContentEntryText(pos=(780,0),size=(100,24),font=1,flags=RT_HALIGN_RIGHT|RT_VALIGN_BOTTOM,text=7),#security MultiContentEntryText(pos=(780,30),size=(100,18),font=1,flags=RT_HALIGN_RIGHT|RT_VALIGN_TOP,text=2),#signal strength MultiContentEntryText(pos=(55,30),size=(220,18),font=1,flags=RT_HALIGN_LEFT|RT_VALIGN_CENTER,text=4),#ip MultiContentEntryText(pos=(605,30),size=(150,18),font=1,flags=RT_HALIGN_RIGHT|RT_VALIGN_CENTER,text=5),#state MultiContentEntryText(pos=(5,0),size=(490,50),font=0,flags=RT_HALIGN_LEFT|RT_VALIGN_CENTER,text=6),#technology name ]), "inputdevice":(50, [ MultiContentEntryText(pos = (5, 0), size = (200, 24), font=0, flags = RT_HALIGN_LEFT, text = 0), #device name MultiContentEntryText(pos = (210, 0), size = (310, 50), font=0, flags = RT_HALIGN_CENTER|RT_VALIGN_CENTER, text = 3), #pairing state MultiContentEntryText(pos = (670, 0), size = (200, 18), font=1, flags = RT_HALIGN_RIGHT|RT_VALIGN_CENTER, text = 4), #connection state MultiContentEntryText(pos = (5, 30), size = (200, 18), font=1, flags = RT_HALIGN_LEFT|RT_VALIGN_CENTER, text = 2), #device address MultiContentEntryText(pos = (670, 30), size = (200, 18), font=1, flags = RT_HALIGN_RIGHT|RT_VALIGN_TOP, text = 1), #rssi ]), }, "fonts": [gFont("Regular",20),gFont("Regular",18)], "itemHeight": 30 } </convert> </widget> <widget name="config" position="250,370" size="950,300" zPosition="1" enableWrapAround="1" scrollbarMode="showOnDemand" transparent="1" /> </screen> """ def __init__(self, session, steps={}): Screen.__init__(self, session, windowTitle=_("Welcome")) self["Title"] = StaticText() self["banner"] = Pixmap() self._text = Label() self["text"] = self._text #buttons self["green"] = Boolean(False) self["green_text"] = Label() self["green_text"].hide() self["yellow"] = Boolean(False) self["yellow_text"] = Label() self["yellow_text"].hide() self["blue"] = Boolean(False) self["blue_text"] = Label() self["blue_text"].hide() #list self.listContent = [] self.list = List(self.listContent) self.list.hide() self["list"] = self.list #config self.configContent = [] self.configList = ConfigList(self.configContent, session=session) self.configList.hide() self["config"] = self.configList self._movingBack = False self._currentStep = None self._stepper = PrioritizedStepper() if not steps: initialSetupSteps.prepare() for s in initialSetupSteps.steps: self.addSteps(s) self["actions"] = NumberActionMap( ["MenuActions", "SetupActions", "ColorActions"], { "ok": self._ok, "cancel": self._cancelAndBack, "menu": self._menu, "left": self.left, "right": self.right, "up": self.up, "down": self.down, "red": self.red, "green": self.green, "yellow": self.yellow, "blue": self.blue, "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.onFirstExecBegin.append(self._nextStep) self.onClose.append(self.__onClose) def __onClose(self): self._stepper.cleanup() self._currentStep = None def _menu(self): choices = [ (_("Cancel guided setup"), self.MENU_CHOICE_LEAVE), ] self.session.openWithCallback(self._onMenuChoice, ChoiceBox, title=_("Menu"), list=choices) def _onMenuChoice(self, choice): choice = choice and choice[1] if not choice: return if choice == self.MENU_CHOICE_LEAVE: self._cancel() def createSummary(self): return SetupGuideSummary def updateSummary(self): if not self._currentStep: return self.summaries.setTitle(self._currentStep.title) summaryText = self._currentStep.text if isinstance(self._currentStep, SetupListStep): current = self.list.current if current: style = self.list.style Log.d("%s - %s" % (current, style)) if style in ("default", "iconized"): summaryText = current[1] elif style == "networkservice": summaryText = current[1].name() elif style == "inputdevice": deviceName = current[1].name() or current[1].shortName( ) or _("DM Remote") summaryText = "%s (%s)" % (deviceName, current[1].address()) else: summaryText = _("n/A") elif isinstance(self._currentStep, SetupConfigStep): current = self.configList.current summaryText = (current and "%s\n%s" % (current[0], _(current[1].getText()))) or _("n/A") Log.d("%s" % (summaryText, )) self.summaries.setText(summaryText) def getText(self): return self._text.getText() def setText(self, text): self._text.setText(text) text = property(getText, setText) def getTitle(self): return Screen.getTitle(self) def setTitle(self, title): Screen.setTitle(self, title) title = property(getTitle, setTitle) def checkButtons(self): keys = ["red", "green", "yellow", "blue"] texts = self._currentStep.buttons() for i in range(1, 4): buttonText = texts[i] key = keys[i] key_text = "%s_text" % (key, ) if buttonText: self[key].boolean = True self[key_text].text = buttonText self[key_text].show() else: self[key].boolean = False self[key_text].text = "" self[key_text].show() def addSteps(self, steps): for prio, step in six.iteritems(steps): self._stepper.add(self, prio, step) def left(self): if isinstance(self._currentStep, SetupConfigStep): self.configList.handleKey(KEY_LEFT) self._currentStep.left() def right(self): if isinstance(self._currentStep, SetupConfigStep): self.configList.handleKey(KEY_RIGHT) self._currentStep.right() def keyNumberGlobal(self, number): if isinstance(self._currentStep, SetupConfigStep): self.configList.handleKey(KEY_0 + number) def up(self): pass def down(self): pass def red(self): pass def green(self): if self._currentStep: self._currentStep.green() def yellow(self): if self._currentStep: self._currentStep.yellow() def blue(self): if self._currentStep: self._currentStep.blue() def nextStep(self): self._nextStep() def _nextStep(self): self._movingBack = False step = self._stepper.next() if step: self._runStep(step) return Log.w("No next step available!") self.close() def _cancelAndBack(self): if self._currentStep: self._currentStep.cancel() self._previousStep() def _previousStep(self): self._movingBack = True step = self._stepper.previous() if step: self._runStep(step) else: Log.w("No previous step available!") self._cancel() def _cancel(self): self.session.openWithCallback( self._onCancelAnswered, MessageBox, _("Do you want to cancel the guided setup?"), type=MessageBox.TYPE_YESNO, windowTitle=_("Cancel guided setup?"), ) def _onCancelAnswered(self, answer): if answer: if self._currentStep: self._currentStep.cancel() self.close() def _ok(self): if self._currentStep.onOk(): self._nextStep() def onSelectionChanged(self): self.updateSummary() def _runStep(self, step): self._currentStep = step self.listContent = [] self.configList.onSelectionChanged = [] self.list.onSelectionChanged = [] if not step.prepare(): if self._movingBack: self._previousStep() else: self.nextStep() return if isinstance(step, SetupListStep): self.configList.hide() self.listContent = step.listContent self.list.list = self.listContent self.list.style = step.listStyle self.list.buildfunc = step.buildfunc self.list.onSelectionChanged = [ step.onSelectionChanged, self.onSelectionChanged ] self.list.index = step.selectedIndex self.list.show() elif isinstance(step, SetupConfigStep): self.list.hide() self.configContent = step.configContent self.configList.list = self.configContent self.configList.onSelectionChanged = [ step.onSelectionChanged, self.onSelectionChanged ] self.configList.show() else: self.configList.hide() self.list.hide() self.setTitle(step.title) self._text.text = step.text self.checkButtons() self.updateSummary()
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()
class Ipkg(Screen): def __init__(self, session, cmdList = None): if not cmdList: cmdList = [] Screen.__init__(self, session) self.setTitle(_('Installing Software...')) 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) 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 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 param not 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 param not 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 param not 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()
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)
class SerienRecorderUpdateScreen(Screen): DESKTOP_WIDTH = getDesktop(0).size().width() DESKTOP_HEIGHT = getDesktop(0).size().height() skin = """ <screen name="SerienRecorderUpdate" position="%d,%d" size="720,320" title="%s" backgroundColor="#26181d20" flags="wfNoBorder"> <widget name="srlog" position="5,5" size="710,310" font="Regular;18" valign="center" halign="center" foregroundColor="white" transparent="1" zPosition="5"/> <widget name="activityslider" position="5,280" size="710,25" borderWidth="1" transparent="1" zPosition="4"/> <widget name="status" position="30,280" size="660,25" font="Regular;20" valign="center" halign="center" foregroundColor="#00808080" transparent="1" zPosition="6"/> </screen>""" % ((DESKTOP_WIDTH - 720) / 2, (DESKTOP_HEIGHT - 320) / 2, _("SerienRecorder Update")) 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) def doActivityTimer(self): if self.downloadDone: self.activity += 1 if self.activity == 101: self.activity = 1 else: if os.path.exists(self.file_name): kBbytesDownloaded = int(os.path.getsize(self.file_name) / 1024) else: kBbytesDownloaded = 0 self.activity = int(kBbytesDownloaded * 100 / self.fileSize) self.status.setText("%s / %s kB (%s%%)" % (kBbytesDownloaded, self.fileSize, self.activity)) self.activityslider.setValue(self.activity) def startActivityTimer(self): self.activityTimer.start(100, False) def stopActivityTimer(self): self.activityTimer.stop() if self.activityTimer: self.activityTimer.stop() self.activityTimer = None if isDreamboxOS: self.activityTimerConnection = None def __onLayoutFinished(self): sl = self['srlog'] sl.instance.setZPosition(5) getPage(str(self.target.replace("/download/", "/tag/").rsplit('/', 1)[0]), timeout=WebTimeout, agent=getUserAgent(), headers={'Content-Type':'application/x-www-form-urlencoded'}).addCallback(self.getFileSize).addErrback(self.downloadError) self['srlog'].setText(_("Download wurde gestartet, bitte warten...")) self.activityslider.setValue(0) self.startActivityTimer() if fileExists(self.file_name): os.remove(self.file_name) downloadPage(self.target, self.file_name).addCallback(self.downloadFinished).addErrback(self.downloadError) def getFileSize(self, data): if isDreamboxOS: raw = re.findall('<a href="/einfall/serienrecorder/releases/download/v.*?/enigma2-plugin-extensions-serienrecorder_.*?_all.deb".*?aria-label="(.*?)">enigma2-plugin-extensions-serienrecorder_.*?_all.deb</span>',data,re.S) else: raw = re.findall('<a href="/einfall/serienrecorder/releases/download/v.*?/enigma2-plugin-extensions-serienrecorder_.*?_all.ipk".*?aria-label="(.*?)">enigma2-plugin-extensions-serienrecorder_.*?_all.ipk</span>',data,re.S) if len(raw): self.fileSize = int(float(raw[0].replace("MB", "").strip()) * 1024.0) else: self.fileSize = 5 * 1024 def downloadFinished(self, data): self.downloadDone = True self.activity = 0 self.status.setText("") if fileExists(self.file_name): self['srlog'].setText("Starte Update, bitte warten...") if isDreamboxOS: self.stdoutAvail_conn = self.container.stdoutAvail.connect(self.srlog) self.appClosed_conn = self.container.appClosed.connect(self.finishedPluginUpdate) self.container.execute("apt-get update && dpkg -i %s && apt-get -f install" % str(self.file_name)) else: self.container.stdoutAvail.append(self.srlog) self.container.appClosed.append(self.finishedPluginUpdate) self.container.execute("opkg update && opkg install --force-overwrite --force-depends --force-downgrade %s" % str(self.file_name)) else: self.downloadError() def downloadError(self): self.stopActivityTimer() writeErrorLog(" SerienRecorderUpdateScreen():\n Url: %s" % self.target) self.session.open(MessageBox, "[SerienRecorder]\nDer Download ist fehlgeschlagen.\nDie Installation wurde abgebrochen.", MessageBox.TYPE_INFO) self.close() def finishedPluginUpdate(self,retval): self.stopActivityTimer() if fileExists(self.file_name): os.remove(self.file_name) self.session.openWithCallback(self.restartGUI, MessageBox, "SerienRecorder wurde erfolgreich aktualisiert!\nWollen Sie jetzt Enigma2 GUI neu starten?", MessageBox.TYPE_YESNO) def restartGUI(self, answer): config.plugins.serienRec.showStartupInfoText.value = True config.plugins.serienRec.showStartupInfoText.save() configfile.save() if answer: self.session.open(Screens.Standby.TryQuitMainloop, 3) else: self.close() def srlog(self,string): self['srlog'].setText(string)
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)
class RadioScreen(Screen, ServiceStopScreen, InfoBarServiceErrorPopupSupport, InfoBarGstreamerErrorPopupSupport): def __init__(self, session): Screen.__init__(self, session, windowTitle=_("Radio")) self.skinName = "SimpleRadioScreen" ServiceStopScreen.__init__(self) self.stopService() self._list = List([], buildfunc=self._buildFunc) self._serviceLabel = Label("") InfoBarServiceErrorPopupSupport.__init__(self) InfoBarGstreamerErrorPopupSupport.__init__(self) self._service = None self.numericalTextInput = NumericalTextInput() self.numericalTextInput.setUseableChars(u'1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ') self["attribution"] = Label(_("powered by www.radio-browser.info")) self["country"] = StaticText("") self["list"] = self._list self["service"] = self._serviceLabel self["actions"] = NumberActionMap(["OkCancelActions", "NumberActions", "ColorActions"], { "ok": self._onOk , "cancel" : self.close, "blue" : self._onBlue, "1": self._onKeyChar, "2": self._onKeyChar, "3": self._onKeyChar, "4": self._onKeyChar, "5": self._onKeyChar, "6": self._onKeyChar, "7": self._onKeyChar, "8": self._onKeyChar, "9": self._onKeyChar, "0": self._onKeyChar }, -1) self._country = config.plugins.simpleradio.country.value self._browser = RadioBrowserClient() self._onLoadFinished({}) self._browser.stations(self._country.lower(), self._onLoadFinished) self["country"].setText(_(self._country.capitalize())) self._browser.countries(self._onCountriesReady) self._stateInfo = self.session.instantiateDialog(InfoBarStateInfo,zPosition=50) self._infoBarStateInfo = InfoBarServiceErrorPopupSupport._stateInfo InfoBarServiceErrorPopupSupport._stateInfo = self._stateInfo self.onClose.append(self.__onClose) def __onClose(self): InfoBarServiceErrorPopupSupport._stateInfo = self._infoBarStateInfo @property def list(self): return self._list.list def _buildFunc(self, station): return [station.name, station.country, station.clickcount, station.bitrate] def _onCountriesReady(self, countries): self._countries = countries def _onBlue(self): if self._countries: self._selectCountry() def _selectCountry(self): if not self._countries: return countries = [("{} ({})".format(_(c.name), c.stationCount), c) for c in self._countries] choices = sorted(countries, key=lambda x: x[0]) self.session.openWithCallback(self._onCountrySelected, ChoiceBox, list=choices, windowTitle=_("Select a country")) def _onCountrySelected(self, country): country = country and country[1] if country: config.plugins.simpleradio.country.value = country.name config.plugins.simpleradio.save() self._country = country.name self._onLoadFinished({}) self._browser.stations(country.name.lower(), self._onLoadFinished) self["country"].setText(_(country.name.capitalize())) def _onLoadFinished(self, stations): lst = [] keys = sorted(stations.keys(), key=lambda x: str(x).lower()) for key in keys: station = stations[key] lst.append((station,)) self._list.list = lst def _onOk(self): station = self._list.getCurrent() station = station and station[0] if station: ref = eServiceReference(eServiceReference.idGST, eServiceReference.isLive, station.urlsResolved[0]) ref.setName(station.name) self._play(ref) def _play(self, service): self._stop() self._service = service self.session.nav.playService(service) self._serviceLabel.setText(self._service.getName()) def _stop(self): self._serviceLabel.setText(_("Please pick a radio stream...")) self._service = None self.session.nav.stopService() def _onKeyChar(self, number): unichar = self.numericalTextInput.getKey(number) charstr = unichar.encode("utf-8") if len(charstr) != 1: return index = 0 for s in self.list: if s[0].name.upper().startswith(charstr): self._list.index = index break index += 1
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()
def setText(self, text): text = (self.displayLength * ' ') + text self.longText = text self.offset = 0 Label.setText(self, text[:self.displayLength].encode('utf-8', 'ignore'))
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()
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
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"
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
class BrowserLauncher(ConfigListScreen, Screen): skin= """ <screen name="BrowserLauncher" position="center,center" size="315,500" title="Web Browser"> <ePixmap pixmap="skin_default/buttons/red.png" position="15,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="155,0" size="140,40" alphatest="on" /> <widget source="key_red" render="Label" position="15,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" transparent="1" /> <widget source="key_green" render="Label" position="155,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" transparent="1" /> <widget name="config" position="0,50" size="309,100" scrollbarMode="showOnDemand" /> <ePixmap pixmap="skin_default/rc_wb_desc.png" position="0,150" size="309,296" alphatest="on" /> <widget name="info" position="0,455" size="309,50" font="Regular;18" halign="center" foregroundColor="blue" transparent="1" /> </screen> """ 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" 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.makeConfig() #time.sleep(2) 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 self.current_lang_idx = language.getActiveLanguageIndex() 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") 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.devices_string = "" self.devices = eConsoleAppContainer() self.devices.dataAvail.append(self.callbackDevicesDataAvail) self.devices.appClosed.append(self.callbakcDevicesAppClose) self.devices.execute(_("cat /proc/bus/input/devices")) def callbackDevicesDataAvail(self, ret_data): self.devices_string = self.devices_string + ret_data def callbakcDevicesAppClose(self, retval): self.name_list = [] self.mouse_list = None self.keyboard_list = None self.makeHandlerList(self.devices_string) if self.conf_mouse == "" or self.getHandlerName(self.conf_mouse) is None: self.conf_mouse = self.mouse_list[0][0] self.mouse = ConfigSelection(default = self.conf_mouse, choices = self.mouse_list) self.list.append(getConfigListEntry(_('Mouse'), self.mouse)) if self.conf_keyboard == "" or self.getHandlerName(self.conf_keyboard) is None: self.conf_keyboard = self.keyboard_list[0][0] self.keyboard = ConfigSelection(default = self.conf_keyboard, choices = self.keyboard_list) 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 makeHandlerList(self, data): n = "" p = "" h_list = [] event_list = [] lines = data.split('\n') for line in lines: print ">>", line if line is not None and len(line) > 0: if line[0] == 'I': n = "" p = "" h_list = [] elif line[0] == 'N': n = line[8:].strip() elif line[0] == 'P': p = line[8:].strip() elif line[0] == 'H': h_list = line[12:].strip().split() tn = line[12:].strip().find("mouse") for h in h_list: event_list.append((h, _(h))) self.name_list.append((h, n)) if n[1:].startswith("dream") and self.rc_mouse is None: self.rc_mouse = copy.deepcopy(h) self.rc_keyboard = copy.deepcopy(h) print "detected!! rc" continue if h.startswith("mouse") and self.usb_mouse is None: self.usb_mouse = copy.deepcopy(h) print "detected!! usb mouse" continue if tn == -1 and self.usb_keyboard is None: self.usb_keyboard = copy.deepcopy(h) print "detected!! usb keyboard" elif line[0] == 'B' and line[3:].startswith("ABS") and p.startswith("usb-"): for h in h_list: if self.usb_mouse is not None: break if self.usb_keyboard is not None and h == self.usb_keyboard[0]: self.usb_keyboard = None print "clean!! usb keyboard" self.usb_mouse = copy.deepcopy(h) print "detected!! usb mouse" tmp = copy.deepcopy(event_list) if self.usb_mouse is not None: tmp.insert(0, ("musb", "USB Mouse")) if self.rc_mouse is not None: tmp.insert(0, ("mrc", "Remote Control")) self.mouse_list = tmp tmp = copy.deepcopy(event_list) if self.usb_keyboard is not None: tmp.insert(0, ("kusb", "USB Keyboard")) if self.rc_keyboard is not None: tmp.insert(0, ("krc", "Remote Control")) self.keyboard_list = tmp print "E:", event_list print "M:", self.mouse_list print "K:", self.keyboard_list 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 if self.mouse.value == "mrc": mouse_param = self.rc_mouse elif self.mouse.value == "musb": mouse_param = self.usb_mouse keyboard_param = self.keyboard.value if self.keyboard.value == "krc": keyboard_param = self.rc_keyboard elif self.keyboard.value == "kusb": keyboard_param = self.usb_keyboard if self.getHandlerName(mouse_param)[1:].startswith("dreambox"): enable_rc_mouse(True) #rc-mouse on if str(mouse_param).startswith("event"): mouse_cmd = "export QWS_MOUSE_PROTO=LinuxInput:/dev/input/%s; " % (str(mouse_param)) keymap_param = "" if self.langs.value == "de": keymap_param = ":keymap=/usr/share/keymaps/player/de.qmap" kbd_cmd = "export QWS_KEYBOARD=LinuxInput:/dev/input/%s%s; " % (str(keyboard_param), keymap_param) 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 getHandlerName(self, v): if v == "mrc": v = self.rc_mouse elif v == "musb": v = self.usb_mouse elif v == "krc": v = self.rc_keyboard elif v == "kusb": v = self.usb_keyboard for l in self.name_list: if l[0] == v: return l[1] return None 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
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)
class BrowserLauncher(ConfigListScreen, Screen): skin = """ <screen name="BrowserLauncher" position="center,center" size="315,500" title="Web Browser"> <ePixmap pixmap="skin_default/buttons/red.png" position="15,0" size="140,40" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="155,0" size="140,40" alphatest="on" /> <widget source="key_red" render="Label" position="15,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" transparent="1" /> <widget source="key_green" render="Label" position="155,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" transparent="1" /> <widget name="config" position="0,50" size="309,100" scrollbarMode="showOnDemand" /> <ePixmap pixmap="skin_default/rc_wb_desc.png" position="0,150" size="309,296" alphatest="on" /> <widget name="info" position="0,455" size="309,50" font="Regular;18" halign="center" foregroundColor="blue" transparent="1" /> </screen> """ 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" 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.makeConfig() #time.sleep(2) 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 self.current_lang_idx = language.getActiveLanguageIndex() 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") 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.devices_string = "" self.devices = eConsoleAppContainer() self.devices.dataAvail.append(self.callbackDevicesDataAvail) self.devices.appClosed.append(self.callbakcDevicesAppClose) self.devices.execute(_("cat /proc/bus/input/devices")) def callbackDevicesDataAvail(self, ret_data): self.devices_string = self.devices_string + ret_data def callbakcDevicesAppClose(self, retval): self.name_list = [] self.mouse_list = None self.keyboard_list = None self.makeHandlerList(self.devices_string) if self.conf_mouse == "" or self.getHandlerName( self.conf_mouse) is None: self.conf_mouse = self.mouse_list[0][0] self.mouse = ConfigSelection(default=self.conf_mouse, choices=self.mouse_list) self.list.append(getConfigListEntry(_('Mouse'), self.mouse)) if self.conf_keyboard == "" or self.getHandlerName( self.conf_keyboard) is None: self.conf_keyboard = self.keyboard_list[0][0] self.keyboard = ConfigSelection(default=self.conf_keyboard, choices=self.keyboard_list) 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 makeHandlerList(self, data): n = "" p = "" h_list = [] event_list = [] lines = data.split('\n') for line in lines: print ">>", line if line is not None and len(line) > 0: if line[0] == 'I': n = "" p = "" h_list = [] elif line[0] == 'N': n = line[8:].strip() elif line[0] == 'P': p = line[8:].strip() elif line[0] == 'H': h_list = line[12:].strip().split() tn = line[12:].strip().find("mouse") for h in h_list: event_list.append((h, _(h))) self.name_list.append((h, n)) if n[1:].startswith("dream") and self.rc_mouse is None: self.rc_mouse = copy.deepcopy(h) self.rc_keyboard = copy.deepcopy(h) print "detected!! rc" continue if h.startswith("mouse") and self.usb_mouse is None: self.usb_mouse = copy.deepcopy(h) print "detected!! usb mouse" continue if tn == -1 and self.usb_keyboard is None: self.usb_keyboard = copy.deepcopy(h) print "detected!! usb keyboard" elif line[0] == 'B' and line[3:].startswith( "ABS") and p.startswith("usb-"): for h in h_list: if self.usb_mouse is not None: break if self.usb_keyboard is not None and h == self.usb_keyboard[ 0]: self.usb_keyboard = None print "clean!! usb keyboard" self.usb_mouse = copy.deepcopy(h) print "detected!! usb mouse" tmp = copy.deepcopy(event_list) if self.usb_mouse is not None: tmp.insert(0, ("musb", "USB Mouse")) if self.rc_mouse is not None: tmp.insert(0, ("mrc", "Remote Control")) self.mouse_list = tmp tmp = copy.deepcopy(event_list) if self.usb_keyboard is not None: tmp.insert(0, ("kusb", "USB Keyboard")) if self.rc_keyboard is not None: tmp.insert(0, ("krc", "Remote Control")) self.keyboard_list = tmp print "E:", event_list print "M:", self.mouse_list print "K:", self.keyboard_list 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 if self.mouse.value == "mrc": mouse_param = self.rc_mouse elif self.mouse.value == "musb": mouse_param = self.usb_mouse keyboard_param = self.keyboard.value if self.keyboard.value == "krc": keyboard_param = self.rc_keyboard elif self.keyboard.value == "kusb": keyboard_param = self.usb_keyboard if self.getHandlerName(mouse_param)[1:].startswith("dreambox"): enable_rc_mouse(True) #rc-mouse on if str(mouse_param).startswith("event"): mouse_cmd = "export QWS_MOUSE_PROTO=LinuxInput:/dev/input/%s; " % ( str(mouse_param)) keymap_param = "" if self.langs.value == "de": keymap_param = ":keymap=/usr/share/keymaps/player/de.qmap" kbd_cmd = "export QWS_KEYBOARD=LinuxInput:/dev/input/%s%s; " % ( str(keyboard_param), keymap_param) 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 getHandlerName(self, v): if v == "mrc": v = self.rc_mouse elif v == "musb": v = self.usb_mouse elif v == "krc": v = self.rc_keyboard elif v == "kusb": v = self.usb_keyboard for l in self.name_list: if l[0] == v: return l[1] return None 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
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 param in self.sliderPackages: 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()
def setText(self, text): text = (self.displayLength * " ") + text self.longText = text self.offset = 0 Label.setText(self, text[: self.displayLength].encode("utf-8", "ignore"))