class Selectmusic(Screen):
	def __init__(self, session):
		Screen.__init__(self, session)
		self["actions"] = HelpableActionMap(self, "MC_AudioPlayerActions",
			{
				"ok": (self.KeyOk, "Play selected file"),
				"left": (self.leftUp, "List Top"),
				"right": (self.rightDown, "List Bottom"),
				"up": (self.up, "List up"),
				"down": (self.down, "List down"),
			}, -2)
		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
			{
				"cancel": self.close
			}, -2)
		currDir = config.plugins.mc_ap.lastDir.value
		if not pathExists(currDir):
			currDir = "/"
		inhibitDirs = ["/bin", "/boot", "/dev", "/dev.static", "/etc", "/lib" , "/proc", "/ram", "/root" , "/sbin", "/sys", "/tmp", "/usr", "/var"]		
		self.filelist = FileList(currDir, useServiceRef = True, showDirectories = True, showFiles = True, matchingPattern = "(?i)^.*\.(m3u|mp2|mp3|wav|wave|pls|wma|m4a|ogg|ra|flac)", inhibitDirs = inhibitDirs)
		self["filelist"] = self.filelist
		self["currentfolder"] = Label()
		self["currentfolder"].setText(str(currDir))
	def up(self):
		self["filelist"].up()
	def down(self):
		self["filelist"].down()
	def leftUp(self):
		self["filelist"].pageUp()
	def rightDown(self):
		self["filelist"].pageDown()
	def KeyOk(self):
		self.filename = self.filelist.getFilename()
		self["currentfolder"].setText(str(self.filelist.getCurrentDirectory()))
		if self.filelist.getFilename() is not None:
			if self.filelist.canDescent():
				self.filelist.descent()
			else:
				config.plugins.mc_pp.music.value = self.filename
				config.plugins.mc_pp.save()
				self.close()
		else:
			if self.filelist.canDescent():
				self.filelist.descent()
			else:
				config.plugins.mc_pp.music.value = self.filename
				config.plugins.mc_pp.save()
				self.close()
class Selectmusic(Screen):
	def __init__(self, session):
		Screen.__init__(self, session)
		self["actions"] = HelpableActionMap(self, "MC_AudioPlayerActions",
			{
				"ok": (self.KeyOk, "Play selected file"),
				"left": (self.leftUp, "List Top"),
				"right": (self.rightDown, "List Bottom"),
				"up": (self.up, "List up"),
				"down": (self.down, "List down"),
			}, -2)
		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
			{
				"cancel": self.close
			}, -2)
		currDir = config.plugins.mc_ap.lastDir.value
		if not pathExists(currDir):
			currDir = "/"
		inhibitDirs = ["/bin", "/boot", "/dev", "/dev.static", "/etc", "/lib" , "/proc", "/ram", "/root" , "/sbin", "/sys", "/tmp", "/usr", "/var"]		
		self.filelist = FileList(currDir, useServiceRef = True, showDirectories = True, showFiles = True, matchingPattern = "(?i)^.*\.(m3u|mp2|mp3|wav|wave|pls|wma|m4a|ogg|ra|flac)", inhibitDirs = inhibitDirs)
		self["filelist"] = self.filelist
		self["currentfolder"] = Label()
		self["currentfolder"].setText(str(currDir))
	def up(self):
		self["filelist"].up()
	def down(self):
		self["filelist"].down()
	def leftUp(self):
		self["filelist"].pageUp()
	def rightDown(self):
		self["filelist"].pageDown()
	def KeyOk(self):
		self.filename = self.filelist.getFilename()
		self["currentfolder"].setText(str(self.filelist.getCurrentDirectory()))
		if self.filelist.getFilename() is not None:
			if self.filelist.canDescent():
				self.filelist.descent()
			else:
				config.plugins.mc_pp.music.value = self.filename
				config.plugins.mc_pp.save()
				self.close()
		else:
			if self.filelist.canDescent():
				self.filelist.descent()
			else:
				config.plugins.mc_pp.music.value = self.filename
				config.plugins.mc_pp.save()
				self.close()
Example #3
0
class DirectoryBrowser(Screen):
    skin = '<screen name="DirectoryBrowser" position="center,center" size="520,440" title=" " >\n\t\t\t<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />\n\t\t\t<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />\n\t\t\t<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />\n\t\t\t<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />\n\t\t\t<widget source="curdir" render="Label" position="5,50" size="510,20"  font="Regular;20" halign="left" valign="center" backgroundColor="background" transparent="1" noWrap="1" />\n\t\t\t<widget name="filelist" position="5,80" size="510,345" scrollbarMode="showOnDemand" />\n\t\t</screen>'

    def __init__(self, session, curdir, matchingPattern=None):
        Screen.__init__(self, session)
        self['Title'].setText(_('Choose dir'))
        self['key_red'] = StaticText(_('Cancel'))
        self['key_green'] = StaticText(_('Save'))
        self['curdir'] = StaticText(_('current:  %s') % (curdir or ''))
        self.filelist = FileList(curdir,
                                 matchingPattern=matchingPattern,
                                 enableWrapAround=True)
        self.filelist.onSelectionChanged.append(self.__selChanged)
        self['filelist'] = self.filelist
        self['FilelistActions'] = ActionMap(
            ['SetupActions', 'ColorActions'], {
                'green': self.keyGreen,
                'red': self.keyRed,
                'ok': self.keyOk,
                'cancel': self.keyRed
            })
        self.onLayoutFinish.append(self.__layoutFinished)

    def __layoutFinished(self):
        pass

    def getCurrentSelected(self):
        dirname = self.filelist.getCurrentDirectory()
        filename = self.filelist.getFilename()
        if not filename and not dirname:
            cur = ''
        elif not filename:
            cur = dirname
        elif not dirname:
            cur = filename
        elif not self.filelist.canDescent() or len(filename) <= len(dirname):
            cur = dirname
        else:
            cur = filename
        return cur or ''

    def __selChanged(self):
        self['curdir'].setText(_('current:  %s') % self.getCurrentSelected())

    def keyOk(self):
        if self.filelist.canDescent():
            self.filelist.descent()

    def keyGreen(self):
        if self.filelist.canDescent() and self.getCurrentSelected():
            self.close(self.getCurrentSelected())

    def keyRed(self):
        self.close(False)
Example #4
0
class EVOMC_AudioPlayer(Screen, HelpableScreen):
	def __init__(self, session):
		Screen.__init__(self, session)
		HelpableScreen.__init__(self)
		self.bScreen = self.session.instantiateDialog(Blackscreen)
		self.bScreen.show()
		self.myaudioScreenSaverconfig = int(config.plugins.EVOMC_saver.myaudioScreenSaver.value)
		self.myaudioScreenSaverTimer = eTimer()
		self.myaudioScreenSaverTimer.timeout.get().append(self.myaudioScreenSaverTimer_Timeout)
		self.ResetmyaudioScreenSaverTimer()
		self.start_timer = eTimer()
		self.moveTimer = eTimer()
		self.start_timer.timeout.get().append(self.onLayoutFinished) 
		self.isVisible = True
		self.oldService = self.session.nav.getCurrentlyPlayingServiceReference()
		self.skindir = "/usr/lib/enigma2/python/Plugins/Extensions/EVOMediaCenter/skins/basic"
		self.coverArtFileName = ""
		self["PositionGauge"] = ServicePositionGauge(self.session.nav)
		self["key_red"] = Button(_("Delete"))
		self["key_green"] = Button(_("Play All"))
		self["key_yellow"] = Button(_("Favorites"))
		self["key_blue"] = Button(_("Settings"))
		self["fileinfo"] = Label()
		self["coverArt"] = MediaPixmap()
		self["currentfolder"] = Label()
		self["currentfavname"] = Label()
		self.playlist = MyPlayList()
		self.currList = "filelist"
		self.curfavfolder = -1
		self["play"] = Pixmap()
		self["stop"] = Pixmap()
		self["curplayingtitle"] = Label()
		self.currPlaying = 0
		self.PlaySingle = 0
		self.PlaySingleRUN = 0
		self.PlayAll = 0
		self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
			{
				iPlayableService.evEOF: self.doEOF,
				iPlayableService.evStopped: self.StopPlayback,
				iPlayableService.evUser+11: self.__evDecodeError,
				iPlayableService.evUser+12: self.__evPluginError,
				iPlayableService.evUser+13: self["coverArt"].embeddedCoverArt
			})
		self["actions"] = HelpableActionMap(self, "EVOMC_AudioPlayerActions",
			{
				"ok": (self.KeyPlaySingle, "Play selected file"),
				"left": (self.leftUp, "List Top"),
				"right": (self.rightDown, "List Bottom"),
				"up": (self.up, "List up"),
				"down": (self.down, "List down"),
				"menu": (self.KeyMenu, "File / Folder Options"),
				"video": (self.visibility, "Show / Hide Player"),
				"nextBouquet": (self.NextFavFolder, "Next Favorite Folder"),
				"prevBouquet": (self.PrevFavFolder, "Previous Favorite Folder"),
				"red": (self.deleteFile, "Delete File"),
				"green": (self.KeyPlayAll, "Play All"),
				"yellow": (self.FavoriteFolders, "Favorite Folders"),
				"blue": (self.Settings, "Settings"),
			}, -2)
		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions",
			{
				"cancel": (self.Exit, "Exit Audio Player"),
			}, -2)
		self["InfobarShowHideActions"] = HelpableActionMap(self, "InfobarShowHideActions",
			{
				"toggleShow": (self.showFileInfo, "Show File Info"),
			}, -2)
		self["MediaPlayerActions"] = HelpableActionMap(self, "MediaPlayerActions",
			{
				"stop": (self.StopPlayback, "Stop Playback"),
			}, -2)
		self.aspect = getAspect()
		currDir = config.plugins.EVOMC_ap.lastDir.value
		if not pathExists(currDir):
			currDir = "/"
		self["currentfolder"].setText(str(currDir))
		self.filelist = FileList(currDir, useServiceRef = True, showDirectories = True, showFiles = True, matchingPattern = "(?i)^.*\.(mp3|ogg|wma|wav|wave|flac|m4a)")
		self["filelist"] = self.filelist
		self["thumbnail"] = Pixmap()
		evfd.getInstance().vfd_write_string("EVO-AUDIOPLAYER")
		self.ThumbTimer = eTimer()
		self.ThumbTimer.callback.append(self.showThumb)
		self.ThumbTimer.start(config.plugins.EVOMC_ap.preview_delay.getValue() * 1000, True)
		self.DimmerTimer = eTimer()
		self.DimmerTimer.callback.append(self.showDimmer)
		self.DimmerTimer.start(config.plugins.EVOMC_all.dimmer_delay.getValue() * 1000, True)
		self.BlinkingPlayIconTimer = eTimer()
		self.BlinkingPlayIconTimer.callback.append(self.BlinkingPlayIcon)
		self.blinking=False
		self.FileInfoTimer = eTimer()
		self.FileInfoTimer.callback.append(self.updateFileInfo)
		self.myaudioScreenSaverconfig = int(config.plugins.EVOMC_saver.myaudioScreenSaver.value)
        	self.ResetmyaudioScreenSaverTimer()
	def onLayoutFinished(self):
        	global startindex
        	self.startindex = startindex
        	self.num += 1
        	if startindex is not None:
            		self.start_timer.stop()
        	else:
            		if self.num < 30:
               			self.start_timer.start(2000)
            		else:
                		self.start_timer.stop()
                		fehler = "Fehler beim automatischen Start"
                		self.session.open(MessageBox,_("%s" %fehler), MessageBox.TYPE_INFO)
	def myaudioScreenSaverTimer_Timeout(self):
        	if self.myaudioScreenSaverTimer.isActive():
        		self.myaudioScreenSaverTimer.stop()
        	self.session.openWithCallback(self.ResetmyaudioScreenSaverTimer,myaudioScreenSaver)
	def ResetmyaudioScreenSaverTimer(self):
        	if onmyaudioScreenSaver:
            		pass
        	if self.myaudioScreenSaverconfig != 0:
            		if self.myaudioScreenSaverTimer.isActive():
                		self.myaudioScreenSaverTimer.stop()
            		self.myaudioScreenSaverTimer.start(self.myaudioScreenSaverconfig * 1000)
	def deleteFile(self):
		if self.currList == "filelist":
			self.service = self.filelist.getServiceRef()
		else:
			self.service = self.playlist.getSelection()
		if self.service is None:
			return
		if self.service.type != 4098 and self.session.nav.getCurrentlyPlayingServiceReference() is not None:
			if self.service == self.session.nav.getCurrentlyPlayingServiceReference():
				self.stopEntry()

		serviceHandler = eServiceCenter.getInstance()
		offline = serviceHandler.offlineOperations(self.service)
		info = serviceHandler.info(self.service)
		name = info and info.getName(self.service)
		result = False
		if offline is not None:
			# simulate first
			if not offline.deleteFromDisk(1):
				result = True
		if result == True:
			self.session.openWithCallback(self.deleteConfirmed_offline, MessageBox, _("Do you really want to delete %s?") % (name))
		else:
			self.session.openWithCallback(self.close, MessageBox, _("You cannot delete this!"), MessageBox.TYPE_ERROR)      

	def deleteConfirmed_offline(self, confirmed):
		if confirmed:
			serviceHandler = eServiceCenter.getInstance()
			offline = serviceHandler.offlineOperations(self.service)
			result = False
			if offline is not None:
				# really delete!
				if not offline.deleteFromDisk(0):
					result = True
			if result == False:
				self.session.open(MessageBox, _("Delete failed!"), MessageBox.TYPE_ERROR)
			else:
				self.removeListEntry()

	def removeListEntry(self):
		self.savePlaylistOnExit = True
		currdir = self.filelist.getCurrentDirectory()
		self.filelist.changeDir(currdir)
		deleteend = False
		while not deleteend:
			index = 0
			deleteend = True
			if len(self.playlist) > 0:
				for x in self.playlist.list:
					if self.service == x[0]:
						self.playlist.deleteFile(index)
						deleteend = False
						break
					index += 1
		self.playlist.updateList()
		if self.currList == "playlist":
			if len(self.playlist) == 0:
				self.switchToFileList()
	def up(self):
		self["filelist"].up()
		system("stfbcontrol a 255")
		self.ThumbTimer.start(config.plugins.EVOMC_ap.preview_delay.getValue() * 1000, True)
		self.DimmerTimer.start(config.plugins.EVOMC_all.dimmer_delay.getValue() * 1000, True)
	def down(self):
		self["filelist"].down()
		system("stfbcontrol a 255")
		self.ThumbTimer.start(config.plugins.EVOMC_ap.preview_delay.getValue() * 1000, True)
		self.DimmerTimer.start(config.plugins.EVOMC_all.dimmer_delay.getValue() * 1000, True)
	def leftUp(self):
		self["filelist"].pageUp()
		system("stfbcontrol a 255")
		self.ThumbTimer.start(config.plugins.EVOMC_ap.preview_delay.getValue() * 1000, True)
		self.DimmerTimer.start(config.plugins.EVOMC_all.dimmer_delay.getValue() * 1000, True)
	def rightDown(self):
		self["filelist"].pageDown()
		system("stfbcontrol a 255")
		self.ThumbTimer.start(config.plugins.EVOMC_ap.preview_delay.getValue() * 1000, True)
		self.DimmerTimer.start(config.plugins.EVOMC_all.dimmer_delay.getValue() * 1000, True)
	def showDimmer(self):
		if config.plugins.EVOMC_all.showDimmer.value:
			system("stfbcontrol a 80")
#		else:
#			pass
	def NextFavFolder(self):
		system("stfbcontrol a 255")
		if self.curfavfolder + 1 < config.plugins.EVOMC_favorites.foldercount.value:
			self.curfavfolder += 1
			self.favname = config.plugins.EVOMC_favorites.folders[self.curfavfolder].name.value
			self.folder = config.plugins.EVOMC_favorites.folders[self.curfavfolder].basedir.value
			self["currentfolder"].setText(("%s") % (self.folder))
			self["currentfavname"].setText(("%s") % (self.favname))
			if pathExists(self.folder) == True:
				self["filelist"].changeDir(self.folder)
		else:
			return
	def PrevFavFolder(self):
		system("stfbcontrol a 255")
		if self.curfavfolder <= 0:
			return
		else:
			self.curfavfolder -= 1
			self.favname = config.plugins.EVOMC_favorites.folders[self.curfavfolder].name.value
			self.folder = config.plugins.EVOMC_favorites.folders[self.curfavfolder].basedir.value
			self["currentfolder"].setText(("%s") % (self.folder))
			self["currentfavname"].setText(("%s") % (self.favname))
			if pathExists(self.folder) == True:
				self["filelist"].changeDir(self.folder)
	def KeyPlaySingle(self):
		filename = self["filelist"].getFilename()
		print "filename", filename
		print "self.PlaySingle", self.PlaySingle
		if self.PlaySingleRUN == 0:
			if self.PlaySingle == 1 or config.plugins.EVOMC_ap.showPreview.getValue():
				if filename.upper().endswith(".MP3") or filename.upper().endswith(".OGG") or filename.upper().endswith(".WAV") or filename.upper().endswith(".WAVE") or filename.upper().endswith(".FLAC") or filename.upper().endswith(".M4A"):
					return
		else:
			if config.plugins.EVOMC_ap.showPreview.getValue():
				if filename.upper().endswith(".MP3") or filename.upper().endswith(".OGG") or filename.upper().endswith(".WAV") or filename.upper().endswith(".WAVE") or filename.upper().endswith(".FLAC") or filename.upper().endswith(".M4A"):
					return
		system("stfbcontrol a 255")
		self.ThumbTimer.stop()
		if self["filelist"].canDescent():
			self["currentfavname"].setText("")
			self.curfavfolder = -1
			self.filelist.descent()
			self["currentfolder"].setText(str(self.filelist.getCurrentDirectory()))
		else:
			self.PlaySingle = 1
			self.PlaySingleRUN = 1
			self.PlayService()
			self.BlinkingPlayIconTimer.stop()
	def KeyPlayAll(self):
		self.ThumbTimer.stop()
		if not self["filelist"].canDescent():
			self.PlaySingle = 0
			self.PlayAll = 1
			self.PlayService()
			self.BlinkingPlayIconTimer.start(1000, True)
	def PlayService(self):
		system("stfbcontrol a 255")
		self.StopPlayback()
		self.filelist.refresh()
		self.currPlaying = 1
		if self.PlayAll == 1:
			self.BlinkingPlayIconTimer.start(1000, True)
		evfd.getInstance().vfd_write_string("PLAY")
		self.session.nav.playService(self["filelist"].getServiceRef())
		self.FileInfoTimer.start(2000, True)
		self["play"].instance.setPixmapFromFile(str(self.skindir) + "/images/icons/play_enabled.png")
		self["stop"].instance.setPixmapFromFile(str(self.skindir) + "/images/icons/stop_disabled.png")
		system("vfdctl +play")
		system("vfdctl +mp3")
		system("vfdctl +music")
		path = self["filelist"].getFilename()
		self["coverArt"].updateCoverArt(path)
	def JumpToFolder(self, jumpto = None):
		if jumpto is None:
			return
		else:
			self["filelist"].changeDir(jumpto)
			self["currentfolder"].setText(("%s") % (jumpto))
	def FavoriteFolders(self):
		self.session.openWithCallback(self.JumpToFolder, EVOMC_FavoriteFolders)
	def StartThumb(self):
		self.session.openWithCallback(self.returnVal, ThumbView, self.filelist.getFileList(), self.filelist.getFilename(), self.filelist.getCurrentDirectory())
	def showThumb(self):
		if config.plugins.EVOMC_ap.showPreview.getValue() == False:
			return
		if self["filelist"].canDescent():
			return
		else:
			if self["filelist"].getServiceRef() is not None:
				system("stfbcontrol a 255")
				self.ThumbTimer.stop()
				system("killall -9 showiframe")
				system("stfbcontrol a 255")
				self.filelist.refresh()
				self.session.nav.stopService()
				self.session.nav.playService(self["filelist"].getServiceRef())
				self.currPlaying = 1
				self["play"].instance.setPixmapFromFile(str(self.skindir) + "/images/icons/play_enabled.png")
				self["stop"].instance.setPixmapFromFile(str(self.skindir) + "/images/icons/stop_disabled.png")
				self.FileInfoTimer.start(2000, True)
				self.BlinkingPlayIconTimer.start(1000, True)
	def returnVal(self, val=0):
		if val > 0:
			for x in self.filelist.getFileList():
				if x[0][1] == True:
					val += 1
			self.filelist.moveToIndex(val)
	def StartExif(self):
		if not self.filelist.canDescent():
			self.session.open(ExifView, self.filelist.getCurrentDirectory() + self.filelist.getFilename(), self.filelist.getFilename())
	def visibility(self, force=1):
		if self.isVisible == True:
			self.isVisible = False
			self.hide()
		else:
			self.isVisible = True
			self.show()
	def BlinkingPlayIcon(self):
		if self.blinking:
			self.blinking=False
			self["play"].instance.setPixmapFromFile(str(self.skindir) + "/images/icons/play_disabled.png")
			self.BlinkingPlayIconTimer.start(1000, True)
		else:
			self.blinking=True
			self["play"].instance.setPixmapFromFile(str(self.skindir) + "/images/icons/play_enabled.png")
			self.BlinkingPlayIconTimer.start(1000, True)
	def StopPlayback(self):
		evfd.getInstance().vfd_write_string("STOP")
		if self.isVisible == False:
			self.show()
			self.isVisible = True
		if self.session.nav.getCurrentService() is None:
			return
		else:
			self.session.nav.stopService()
			self["play"].instance.setPixmapFromFile(str(self.skindir) + "/images/icons/play_disabled.png")
			self["stop"].instance.setPixmapFromFile(str(self.skindir) + "/images/icons/stop_enabled.png")
			self.currPlaying = 0
			self.BlinkingPlayIconTimer.stop()
			self.ThumbTimer.stop()
			system("killall -9 showiframe")
			system("stfbcontrol a 255")
			self.ThumbTimer.start(config.plugins.EVOMC_ap.preview_delay.getValue() * 1000, True)
			self.DimmerTimer.start(config.plugins.EVOMC_all.dimmer_delay.getValue() * 1000, True)
			system("vfdctl -play")
			system("vfdctl -mp3")
			system("vfdctl -music")
			self.StopPlayback()
	def showFileInfo(self):
		if self["filelist"].canDescent():
			return
		else:
			system("stfbcontrol a 255")
			self.ThumbTimer.start(config.plugins.EVOMC_ap.preview_delay.getValue() * 1000, True)
			self.DimmerTimer.start(config.plugins.EVOMC_all.dimmer_delay.getValue() * 1000, True)
			self.session.open(EVOMC_AudioInfoView, self["filelist"].getCurrentDirectory() + self["filelist"].getFilename() , self["filelist"].getFilename(), self["filelist"].getServiceRef())
	def updateFileInfo(self):
		if self["filelist"].canDescent():
			return
		currPlay = self.session.nav.getCurrentService()
		if currPlay is not None:
			stitle = currPlay.info().getInfoString(iServiceInformation.sTagTitle)
			sArtist = currPlay.info().getInfoString(iServiceInformation.sTagArtist)
			sAlbum = currPlay.info().getInfoString(iServiceInformation.sTagAlbum)
			sGenre = currPlay.info().getInfoString(iServiceInformation.sTagGenre)
			sYear = currPlay.info().getInfoString(iServiceInformation.sTimeCreate)
#			sComment = currPlay.info().getInfoString(iServiceInformation.sTagComment)
			if stitle == "":
				stitle = currPlay.info().getName().split('/')[-1]
			self["fileinfo"].setText("Title: " + stitle + "\nArtist: " +  sArtist + "\nAlbum: " + sAlbum + "\nGenre: " + sGenre)
			self["curplayingtitle"].setText(stitle)
		else:
			pass
	def doEOF(self):
		try:
			print "EVO-MediaCenter: EOF Event ..."
			if self.PlaySingle == 0:
				print "Play Next File ..."
				self.ThumbTimer.stop()
				self.down()
				try:
					self.PlayService()
				except:
					pass
			else:
				print "Stop Playback ..."
				self.StopPlayback()
				system("vfdctl -play")
				system("vfdctl -mp3")
				system("vfdctl -music")
		except:
			pass
	def __evDecodeError(self):
		currPlay = self.session.nav.getCurrentService()
		sAudioType = currPlay.info().getInfoString(iServiceInformation.sUser+10)
		print "[__evAudioDecodeError] audio-codec %s can't be decoded by hardware" % (sAudioType)
		self.session.open(MessageBox, _("This UFS can't decode %s streams!") % sAudioType, type = MessageBox.TYPE_INFO,timeout = 5 )
	def __evPluginError(self):
		currPlay = self.session.nav.getCurrentService()
		message = currPlay.info().getInfoString(iServiceInformation.sUser+12)
		print "[__evPluginError]" , message
		self.session.open(MessageBox, message, type = MessageBox.TYPE_INFO,timeout = 20 )
	def Playlists(self):
		evfd.getInstance().vfd_write_string("PLAYLIST")
		self.ThumbTimer.stop()
		self.session.open(MessageBox,"Coming soon ... :)",  MessageBox.TYPE_INFO)
	def KeyMenu(self):
		self.ThumbTimer.stop()
		if self["filelist"].canDescent():
			if self.filelist.getCurrent()[0][1]:
				self.currentDirectory = self.filelist.getCurrent()[0][0]
				self.foldername = self.currentDirectory.split('/')
				self.foldername = self.foldername[-2]
				self.session.open(EVOMC_FolderOptions, self.currentDirectory, self.foldername)
	def Settings(self):
		evfd.getInstance().vfd_write_string("SETTINGS")
		system("stfbcontrol a 255")
		self.ThumbTimer.stop()
		self.session.open(AudioPlayerSettings)
		config.plugins.EVOMC_ap.save()
		config.plugins.EVOMC_all.save()
	def Exit(self):
		if self.isVisible == False:
			self.visibility()
			return
		if self.filelist.getCurrentDirectory() is None:
			config.plugins.EVOMC_ap.lastDir.value = "/"
		else:
			config.plugins.EVOMC_ap.lastDir.value = self.filelist.getCurrentDirectory()
		system("killall -9 showiframe")
		system("stfbcontrol a 255")
		system("vfdctl -play")
		system("vfdctl -mp3")
		system("vfdctl -music")
		self.ThumbTimer.stop()
		self.DimmerTimer.stop()
		self.FileInfoTimer.stop()
		del self["coverArt"].picload
		config.plugins.EVOMC_ap.save()
		config.plugins.EVOMC_all.save()
		self.session.nav.stopService()
		evfd.getInstance().vfd_write_string("EVO-MediaCenter")
		self.close()
class FlashImageConfig(Screen):
	def __init__(self, session, curdir, matchingPattern=None):
		try:
			sz_w = getDesktop(0).size().width()
		except:
			sz_w = 720
		if sz_w >= 1280:
			self.skin = skinflashhd
		else:
			self.skin = skinflashsd

		Screen.__init__(self, session)
		self["Title"].setText(_("Select the folder with backup"))
		self["key_red"] = StaticText(_("Cancel"))
		self["key_green"] = StaticText("")
		self["key_yellow"] = StaticText("")
		self["curdir"] = StaticText(_("current:  %s")%(curdir or ''))
		self.founds = False
		self.filelist = FileList(curdir, matchingPattern=matchingPattern, enableWrapAround=True)
		self.filelist.onSelectionChanged.append(self.__selChanged)
		self["filelist"] = self.filelist

		self["FilelistActions"] = ActionMap(["SetupActions", "ColorActions"],
			{
				"green": self.keyGreen,
				"red": self.keyRed,
				"yellow": self.keyYellow,
				"ok": self.keyOk,
				"cancel": self.keyRed
			})
		self.onLayoutFinish.append(self.__layoutFinished)

	def __layoutFinished(self):
		pass

	def getCurrentSelected(self):
		dirname = self.filelist.getCurrentDirectory()
		filename = self.filelist.getFilename()
		if not filename and not dirname:
			cur = ''
		elif not filename:
			cur = dirname
		elif not dirname:
			cur = filename
		else:
			if not self.filelist.canDescent() or len(filename) <= len(dirname):
				cur = dirname
			else:
				cur = filename
		return cur or ''

	def __selChanged(self):
		self["key_yellow"].setText("")
		self["key_green"].setText("")
		self["curdir"].setText(_("current:  %s")%(self.getCurrentSelected()))
		file_name = self.getCurrentSelected()
		try:
			if not self.filelist.canDescent() and file_name != '' and file_name != '/':
				filename = self.filelist.getFilename()
				if filename and filename.endswith(".zip"):
					self["key_yellow"].setText(_("Unzip"))
			elif self.filelist.canDescent() and file_name != '' and file_name != '/':
				self["key_green"].setText(_("Run flash"))
		except:
			pass

	def keyOk(self):
		if self.filelist.canDescent():
			self.filelist.descent()

	def confirmedWarning(self, result):
		if result:
			self.founds = False
			self.showparameterlist()

	def keyGreen(self):
		if self["key_green"].getText() == _("Run flash"):
			dirname = self.filelist.getCurrentDirectory()
			if dirname:
				self.session.openWithCallback(lambda r: self.confirmedWarning(r), MessageBox, _("Warning!\nUse at your own risk! Make always a backup before use!\nDon't use it if you use multiple ubi volumes in ubi layer!") , MessageBox.TYPE_INFO)

	def showparameterlist(self):
		if self["key_green"].getText() == _("Run flash"):
			dirname = self.getCurrentSelected()
			if dirname:
				backup_files = []
				no_backup_files = []
				text = _("Select parameter for start flash!\n")
				text += _('For flashing your receiver files are needed:\n')
				
				# refer to /proc/stb/info/hwmodel file.
				if os.path.exists("/proc/stb/info/hwmodel"):
					f = open("/proc/stb/info/hwmodel")
					model = f.read().strip()
					f.close()
					if model in ["force1", "force1plus", "twin", "2T", "nano", "single", "nano2T", "ios100", "ios200", "ios300", "ios300NEW", "optimussos1", "optimussos2", "tmnano2super", "tmnano3tcombo", "tmnanose", "tmnanosecombo", "tmnanoeco", "force2", "force2plus", "optimussos1plus", "optimussos2plus", "optimussos3plus"]:
						backup_files = [("oe_kernel"), ("oe_rootfs.bin")]
						no_backup_files = ["oe_kernel.bin", "oe_rootfs.bin", "oe_rootfs.bin"]
						text += 'oe_kernel.bin, oe_rootfs.bin'
					else:
						backup_files = ["kernel_cfe_auto.bin", "root_cfe_auto.jffs2"]
						no_backup_files = ["kernel.bin", "root_cfe_auto.bin", "rootfs.bin"]
						text += 'kernel_cfe_auto.bin, root_cfe_auto.jffs2'
#				if os.path.exists("/proc/stb/info/boxtype"):
#					backup_files = [("kernel.bin"), ("rootfs.bin")]
#					no_backup_files = ["kernel_cfe_auto.bin", "root_cfe_auto.jffs2", "root_cfe_auto.bin"]
#					text += 'kernel.bin, rootfs.bin'
#				elif os.path.exists("/proc/stb/info/vumodel"):
#					f = open("/proc/stb/info/vumodel")
#					model = f.read().strip()
#					f.close()
#					if model in ["solo2", "duo2"]:
#						backup_files = ["kernel_cfe_auto.bin", "root_cfe_auto.bin"]
#						no_backup_files = ["kernel.bin", "root_cfe_auto.jffs2", "rootfs.bin"]
#						text += 'kernel_cfe_auto.bin, root_cfe_auto.bin'

				try:
					self.founds = False
					text += _('\nThe found files:')
					for name in os.listdir(dirname):
						if name in backup_files:
							text += _("  %s (maybe ok)") % name
							self.founds = True
						if name in no_backup_files:
							text += _("  %s (maybe error)") % name
							self.founds = True
					if not self.founds:
						text += _(' nothing!')
				except:
					pass
				if self.founds:
					open_list = [
						(_("Simulate (no write)"), "simulate"),
						(_("Standard (root and kernel)"), "Standard"),
						(_("Only root"), "root"),
						(_("Only kernel"), "kernel"),
						(_("Only root with use mtdy device"), "mtdy"),
						(_("Only kernel with use mtdx device"), "mtdx"),
					]
				else:
					open_list = [
						(_("Exit"), "exit"),
					]
				self.session.openWithCallback(self.Callbackflashing, MessageBox, text, simple = True, list = open_list)

	def Callbackflashing(self, ret):
		if ret:
			if ret == "exit":
				self.close()
				return
			if self.session.nav.RecordTimer.isRecording():
				self.session.open(MessageBox, _("A recording is currently running. Please stop the recording before trying to start a flashing."), MessageBox.TYPE_ERROR)
				self.founds = False
				return
			dir_flash = self.getCurrentSelected()
			text = _("Flashing: ")
			cmd = "echo -e"
			if ret == "simulate":
				text += _("Simulate (no write)")
				cmd = "%s -n '%s'" % (ofgwrite_bin, dir_flash)
			elif ret == "Standard":
				text += _("Standard (root and kernel)")
				cmd = "%s -r -k '%s' > /dev/null 2>&1 &" % (ofgwrite_bin, dir_flash)
			elif ret == "root":
				text += _("Only root")
				cmd = "%s -r '%s' > /dev/null 2>&1 &" % (ofgwrite_bin, dir_flash)
			elif ret == "kernel":
				text += _("Only kernel")
				cmd = "%s -k '%s' > /dev/null 2>&1 &" % (ofgwrite_bin, dir_flash)
			elif ret == "mtdy":
				text += _("Only root with use mtdy device")
				cmd = "%s -rmtdy '%s' > /dev/null 2>&1 &" % (ofgwrite_bin, dir_flash)
			elif ret == "mtdx":
				text += _("Only kernel with use mtdx device")
				cmd = "%s -kmtdx '%s' > /dev/null 2>&1 &" % (ofgwrite_bin, dir_flash)
			else:
				return
			message = "echo -e '\n"
			message += _('NOT found files for flashing!\n')
			message += "'"
			if ret != "simulate":
				if self.founds:
					message = "echo -e '\n"
					message += _('ofgwrite will stop enigma2 now to run the flash.\n')
					message += _('Your STB will freeze during the flashing process.\n')
					message += _('Please: DO NOT reboot your STB and turn off the power.\n')
					message += _('The image or kernel will be flashing and auto booted in few minutes.\n')
					message += "'"
			else:
				if self.founds:
					message = "echo -e '\n"
					message += _('Show only found image and mtd partitions.\n')
					message += "'"
			try:
				if os.path.exists(ofgwrite_bin):
					os.chmod(ofgwrite_bin, 0755)
			except:
				pass
			self.session.open(Console, text,[message, cmd])

	def keyRed(self):
		self.close()

	def keyYellow(self):
		if self["key_yellow"].getText() == _("Unzip"):
			filename = self.filelist.getFilename()
			if filename and filename.endswith(".zip"):
				self.session.openWithCallback(self.doUnzip, MessageBox, _("Do you really want to unpack %s ?") % filename, MessageBox.TYPE_YESNO)

	def doUnzip(self, answer):
		if answer is True:
			dirname = self.filelist.getCurrentDirectory()
			filename = self.filelist.getFilename()
			if dirname and filename:
				try:
					os.system('unzip -o %s%s -d %s'%(dirname,filename,dirname))
					self.filelist.refresh()
				except:
					pass
Example #6
0
class DirectoryBrowser(Screen):
    skin = """<screen name="DirectoryBrowser" position="center,center" size="520,440" title="Directory browser" >
			<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
			<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
			<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
			<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
			<widget source="curdir" render="Label" position="5,50" size="510,20"  font="Regular;20" halign="left" valign="center" backgroundColor="background" transparent="1" noWrap="1" />
			<widget name="filelist" position="5,80" size="510,345" scrollbarMode="showOnDemand" />
		</screen>"""

    def __init__(self, session, curdir, matchingPattern=None):
        Screen.__init__(self, session)

        self["key_red"] = StaticText(_("Cancel"))
        self["key_green"] = StaticText(_("Save"))
        self["curdir"] = StaticText("current:  %s" % (curdir or ''))

        self.filelist = FileList(curdir,
                                 matchingPattern=matchingPattern,
                                 enableWrapAround=True)
        self.filelist.onSelectionChanged.append(self.__selChanged)
        self["filelist"] = self.filelist

        self["FilelistActions"] = ActionMap(
            ["SetupActions", "ColorActions"], {
                "green": self.keyGreen,
                "red": self.keyRed,
                "ok": self.keyOk,
                "cancel": self.keyRed
            })
        self.onLayoutFinish.append(self.__layoutFinished)

    def __layoutFinished(self):
        #self.setTitle(_("Directory browser"))
        pass

    def getCurrentSelected(self):
        dirname = self.filelist.getCurrentDirectory()
        filename = self.filelist.getFilename()
        if not filename and not dirname:
            cur = ''
        elif not filename:
            cur = dirname
        elif not dirname:
            cur = filename
        else:
            if not self.filelist.canDescent() or len(filename) <= len(dirname):
                cur = dirname
            else:
                cur = filename
        return cur or ''

    def __selChanged(self):
        self["curdir"].setText("current:  %s" % (self.getCurrentSelected()))

    def keyOk(self):
        if self.filelist.canDescent():
            self.filelist.descent()

    def keyGreen(self):
        self.close(self.getCurrentSelected())

    def keyRed(self):
        self.close(False)
Example #7
0
class FlashImageConfig(Screen):
    def __init__(self, session, curdir, matchingPattern=None):
        try:
            sz_w = getDesktop(0).size().width()
        except:
            sz_w = 720
        if sz_w == 1920:
            self.skin = skinflashfullhd
        elif sz_w >= 1280:
            self.skin = skinflashhd
        else:
            self.skin = skinflashsd
        Screen.__init__(self, session)
        self.skin_path = resolveFilename(SCOPE_PLUGINS,
                                         "Extensions/BackupSuite")
        self["Title"].setText(_("Select the folder with backup"))
        self["key_red"] = StaticText(_("Close"))
        self["key_green"] = StaticText("")
        self["key_yellow"] = StaticText("")
        self["key_blue"] = StaticText("")
        self["curdir"] = StaticText(_("current:  %s") % (curdir or ''))
        self.founds = False
        self.dualboot = self.dualBoot()
        self.ForceMode = self.ForceMode()
        self.filelist = FileList(curdir,
                                 matchingPattern=matchingPattern,
                                 enableWrapAround=True)
        self.filelist.onSelectionChanged.append(self.__selChanged)
        self["filelist"] = self.filelist
        self["FilelistActions"] = ActionMap(
            ["SetupActions", "ColorActions"], {
                "green": self.keyGreen,
                "red": self.keyRed,
                "yellow": self.keyYellow,
                "blue": self.KeyBlue,
                "ok": self.keyOk,
                "cancel": self.keyRed
            })
        self.onLayoutFinish.append(self.__layoutFinished)

    def __layoutFinished(self):
        pass

    def dualBoot(self):
        if getBoxType() == "et8500":
            rootfs2 = False
            kernel2 = False
            f = open("/proc/mtd")
            l = f.readlines()
            for x in l:
                if 'rootfs2' in x:
                    rootfs2 = True
                if 'kernel2' in x:
                    kernel2 = True
            f.close()
            if rootfs2 and kernel2:
                return True
        return False

    def ForceMode(self):
        if getBoxType() in ("h9", "h9se", "h9combo", "h9combose", "i55plus",
                            "i55se", "h10", "hzero", "h8"):
            return True
        return False

    def getCurrentSelected(self):
        dirname = self.filelist.getCurrentDirectory()
        filename = self.filelist.getFilename()
        if not filename and not dirname:
            cur = ''
        elif not filename:
            cur = dirname
        elif not dirname:
            cur = filename
        else:
            if not self.filelist.canDescent() or len(filename) <= len(dirname):
                cur = dirname
            else:
                cur = filename
        return cur or ''

    def __selChanged(self):
        self["key_yellow"].setText("")
        self["key_green"].setText("")
        self["key_blue"].setText("")
        self["curdir"].setText(_("current:  %s") % (self.getCurrentSelected()))
        file_name = self.getCurrentSelected()
        try:
            if not self.filelist.canDescent(
            ) and file_name != '' and file_name != '/':
                filename = self.filelist.getFilename()
                if filename and filename.endswith(".zip"):
                    self["key_yellow"].setText(_("Unzip"))
            elif self.filelist.canDescent(
            ) and file_name != '' and file_name != '/':
                self["key_green"].setText(_("Run flash"))
                if os.path.isfile(file_name +
                                  LOGFILE) and os.path.isfile(file_name +
                                                              VERSIONFILE):
                    self["key_yellow"].setText(_("Backup info"))
                    self["key_blue"].setText(_("Delete"))
        except:
            pass

    def keyOk(self):
        if self.filelist.canDescent():
            self.filelist.descent()

    def confirmedWarning(self, result):
        if result:
            self.founds = False
            self.showparameterlist()

    def keyGreen(self):
        if self["key_green"].getText() == _("Run flash"):
            dirname = self.filelist.getCurrentDirectory()
            if dirname:
                warning_text = "\n"
                if self.dualboot:
                    warning_text += _("\nYou are using dual multiboot!")
                self.session.openWithCallback(
                    lambda r: self.confirmedWarning(r), MessageBox,
                    _("Warning!\nUse at your own risk! Make always a backup before use!\nDon't use it if you use multiple ubi volumes in ubi layer!"
                      ) + warning_text, MessageBox.TYPE_INFO)

    def showparameterlist(self):
        if self["key_green"].getText() == _("Run flash"):
            dirname = self.getCurrentSelected()
            model = getBoxType()
            if dirname:
                backup_files = []
                no_backup_files = []
                text = _("Select parameter for start flash!\n")
                text += _('For flashing your receiver files are needed:\n')
                if model.startswith("dm"):
                    if "dm9" in model:
                        backup_files = [("kernel.bin"), ("rootfs.tar.bz2")]
                        no_backup_files = [("kernel_cfe_auto.bin"),
                                           ("rootfs.bin"),
                                           ("root_cfe_auto.jffs2"),
                                           ("root_cfe_auto.bin"),
                                           ("oe_kernel.bin"),
                                           ("oe_rootfs.bin"),
                                           ("kernel_auto.bin"), ("uImage"),
                                           ("rootfs.ubi")]
                        text += "kernel.bin, rootfs.tar.bz2"
                    elif model in ("dm520", "dm7080", "dm820"):
                        backup_files = [("*.xz")]
                        no_backup_files = [("kernel_cfe_auto.bin"),
                                           ("rootfs.bin"),
                                           ("root_cfe_auto.jffs2"),
                                           ("root_cfe_auto.bin"),
                                           ("oe_kernel.bin"),
                                           ("oe_rootfs.bin"),
                                           ("kernel_auto.bin"), ("kernel.bin"),
                                           ("rootfs.tar.bz2"), ("uImage"),
                                           ("rootfs.ubi")]
                        text += "*.xz"
                    else:
                        backup_files = [("*.nfi")]
                        no_backup_files = [("kernel_cfe_auto.bin"),
                                           ("rootfs.bin"),
                                           ("root_cfe_auto.jffs2"),
                                           ("root_cfe_auto.bin"),
                                           ("oe_kernel.bin"),
                                           ("oe_rootfs.bin"),
                                           ("kernel_auto.bin"), ("kernel.bin"),
                                           ("rootfs.tar.bz2"), ("uImage"),
                                           ("rootfs.ubi")]
                        text += "*.nfi"
                elif model.startswith("gb"):
                    if not "4k" in model:
                        backup_files = [("kernel.bin"), ("rootfs.bin")]
                        no_backup_files = [("kernel_cfe_auto.bin"),
                                           ("root_cfe_auto.jffs2"),
                                           ("root_cfe_auto.bin"),
                                           ("oe_kernel.bin"),
                                           ("oe_rootfs.bin"),
                                           ("rootfs.tar.bz2"),
                                           ("kernel_auto.bin"), ("uImage"),
                                           ("rootfs.ubi")]
                        text += "kernel.bin, rootfs.bin"
                    else:
                        backup_files = [("kernel.bin"), ("rootfs.tar.bz2")]
                        no_backup_files = [("kernel_cfe_auto.bin"),
                                           ("rootfs.bin"),
                                           ("root_cfe_auto.jffs2"),
                                           ("root_cfe_auto.bin"),
                                           ("oe_kernel.bin"),
                                           ("oe_rootfs.bin"),
                                           ("kernel_auto.bin"), ("uImage"),
                                           ("rootfs.ubi")]
                        text += "kernel.bin, rootfs.tar.bz2"
                elif model.startswith("vu"):
                    if "4k" in model:
                        backup_files = [("kernel_auto.bin"),
                                        ("rootfs.tar.bz2")]
                        no_backup_files = [("kernel_cfe_auto.bin"),
                                           ("rootfs.bin"),
                                           ("root_cfe_auto.jffs2"),
                                           ("root_cfe_auto.bin"),
                                           ("oe_kernel.bin"),
                                           ("oe_rootfs.bin"), ("kernel.bin"),
                                           ("uImage"), ("rootfs.ubi")]
                        text += "kernel_auto.bin, rootfs.tar.bz2"
                    elif model in ("vuduo2", "vusolose", "vusolo2", "vuzero"):
                        backup_files = [("kernel_cfe_auto.bin"),
                                        ("root_cfe_auto.bin")]
                        no_backup_files = [("rootfs.bin"),
                                           ("root_cfe_auto.jffs2"),
                                           ("oe_kernel.bin"),
                                           ("oe_rootfs.bin"), ("kernel.bin"),
                                           ("rootfs.tar.bz2"),
                                           ("kernel_auto.bin"), ("uImage"),
                                           ("rootfs.ubi")]
                        text += "kernel_cfe_auto.bin, root_cfe_auto.bin"
                    else:
                        backup_files = [("kernel_cfe_auto.bin"),
                                        ("root_cfe_auto.jffs2")]
                        no_backup_files = [("rootfs.bin"),
                                           ("root_cfe_auto.bin"),
                                           ("oe_kernel.bin"),
                                           ("oe_rootfs.bin"), ("kernel.bin"),
                                           ("rootfs.tar.bz2"),
                                           ("kernel_auto.bin"), ("uImage"),
                                           ("rootfs.ubi")]
                        text += "kernel_cfe_auto.bin, root_cfe_auto.jffs2"

                else:
                    if model in ("hd51", "h7", "sf4008", "sf5008", "sf8008",
                                 "sf8008m", "vs1500", "et11000", "et13000",
                                 "bre2ze4k", "spycat4k", "spycat4kmini",
                                 "protek4k", "e4hdultra", "arivacombo",
                                 "arivatwin") or model.startswith(
                                     ("anadol", "axashis4", "dinobot4",
                                      "ferguson4", "mediabox4", "axashisc4")):
                        backup_files = [("kernel.bin"), ("rootfs.tar.bz2")]
                        no_backup_files = [("kernel_cfe_auto.bin"),
                                           ("rootfs.bin"),
                                           ("root_cfe_auto.jffs2"),
                                           ("root_cfe_auto.bin"),
                                           ("oe_kernel.bin"),
                                           ("oe_rootfs.bin"),
                                           ("kernel_auto.bin"), ("uImage"),
                                           ("rootfs.ubi")]
                        text += "kernel.bin, rootfs.tar.bz2"
                    elif model in ("h9", "h9se", "h9combo", "h9combose",
                                   "i55plus", "i55se", "h10", "hzero", "h8",
                                   "dinobotu55", "iziboxx3", "dinoboth265",
                                   "axashistwin", "protek4kx1"):
                        backup_files = [("uImage"), ("rootfs.ubi")]
                        no_backup_files = [("kernel_cfe_auto.bin"),
                                           ("root_cfe_auto.jffs2"),
                                           ("root_cfe_auto.bin"),
                                           ("oe_kernel.bin"),
                                           ("oe_rootfs.bin"),
                                           ("rootfs.tar.bz2"),
                                           ("kernel_auto.bin"), ("kernel.bin"),
                                           ("rootfs.tar.bz2")]
                        text += "uImage, rootfs.ubi"
                    elif model in ("hd60", "hd61", "multibox", "multiboxplus"):
                        backup_files = [("uImage"), ("rootfs.tar.bz2")]
                        no_backup_files = [("kernel_cfe_auto.bin"),
                                           ("root_cfe_auto.jffs2"),
                                           ("root_cfe_auto.bin"),
                                           ("oe_kernel.bin"),
                                           ("oe_rootfs.bin"), ("rootfs.ubi"),
                                           ("kernel_auto.bin"), ("kernel.bin")]
                        text += "uImage, rootfs.tar.bz2"
                    elif model.startswith(
                        ("et4", "et5", "et6", "et7", "et8", "et9", "et10")):
                        backup_files = [("kernel.bin"), ("rootfs.bin")]
                        no_backup_files = [("kernel_cfe_auto.bin"),
                                           ("root_cfe_auto.jffs2"),
                                           ("root_cfe_auto.bin"),
                                           ("oe_kernel.bin"),
                                           ("oe_rootfs.bin"),
                                           ("rootfs.tar.bz2"),
                                           ("kernel_auto.bin"), ("uImage"),
                                           ("rootfs.ubi")]
                        text += "kernel.bin, rootfs.bin"
                    elif model.startswith("ebox"):
                        backup_files = [("kernel_cfe_auto.bin"),
                                        ("root_cfe_auto.jffs2")]
                        no_backup_files = [("rootfs.bin"),
                                           ("root_cfe_auto.bin"),
                                           ("oe_kernel.bin"),
                                           ("oe_rootfs.bin"), ("kernel.bin"),
                                           ("rootfs.tar.bz2"),
                                           ("kernel_auto.bin"), ("uImage"),
                                           ("rootfs.ubi")]
                        text += "kernel_cfe_auto.bin, root_cfe_auto.jffs2"
                    elif model.startswith(
                        ("fusion", "pure", "optimus", "force", "iqon", "ios",
                         "tm2", "tmn", "tmt", "tms", "lunix", "mediabox",
                         "vala")):
                        backup_files = [("oe_kernel.bin"), ("oe_rootfs.bin")]
                        no_backup_files = [("kernel_cfe_auto.bin"),
                                           ("rootfs.bin"),
                                           ("root_cfe_auto.jffs2"),
                                           ("root_cfe_auto.bin"),
                                           ("kernel.bin"), ("rootfs.tar.bz2"),
                                           ("kernel_auto.bin"), ("uImage"),
                                           ("rootfs.ubi")]
                        text += "oe_kernel.bin, oe_rootfs.bin"
                    elif "4k" or "uhd" in model:
                        backup_files = [("oe_kernel.bin"), ("rootfs.tar.bz2")]
                        no_backup_files = [("kernel_cfe_auto.bin"),
                                           ("rootfs.bin"),
                                           ("root_cfe_auto.jffs2"),
                                           ("root_cfe_auto.bin"),
                                           ("oe_rootfs.bin"), ("kernel.bin"),
                                           ("kernel_auto.bin"), ("uImage"),
                                           ("rootfs.ubi")]
                        text += "oe_kernel.bin, rootfs.tar.bz2"
                    else:
                        backup_files = [("kernel.bin"), ("rootfs.bin")]
                        no_backup_files = [("kernel_cfe_auto.bin"),
                                           ("root_cfe_auto.jffs2"),
                                           ("root_cfe_auto.bin"),
                                           ("oe_kernel.bin"),
                                           ("oe_rootfs.bin"),
                                           ("rootfs.tar.bz2"),
                                           ("kernel_auto.bin"), ("uImage"),
                                           ("rootfs.ubi")]
                        text += "kernel.bin, rootfs.bin"
                try:
                    self.founds = False
                    text += _('\nThe found files:')
                    for name in os.listdir(dirname):
                        if name in backup_files:
                            text += _("  %s (maybe ok)") % name
                            self.founds = True
                        if name in no_backup_files:
                            text += _("  %s (maybe error)") % name
                            self.founds = True
                    if not self.founds:
                        text += _(' nothing!')
                except:
                    pass
                if self.founds:
                    open_list = [
                        (_("Simulate (no write)"), "simulate"),
                        (_("Standard (root and kernel)"), "standard"),
                        (_("Only root"), "root"),
                        (_("Only kernel"), "kernel"),
                    ]
                    open_list2 = [
                        (_("Simulate second partition (no write)"),
                         "simulate2"),
                        (_("Second partition (root and kernel)"), "standard2"),
                        (_("Second partition (only root)"), "rootfs2"),
                        (_("Second partition (only kernel)"), "kernel2"),
                    ]
                    if self.dualboot:
                        open_list += open_list2
                else:
                    open_list = [
                        (_("Exit"), "exit"),
                    ]
                self.session.openWithCallback(self.Callbackflashing,
                                              MessageBox,
                                              text,
                                              simple=True,
                                              list=open_list)

    def Callbackflashing(self, ret):
        if ret:
            if ret == "exit":
                self.close()
                return
            if self.session.nav.RecordTimer.isRecording():
                self.session.open(
                    MessageBox,
                    _("A recording is currently running. Please stop the recording before trying to start a flashing."
                      ), MessageBox.TYPE_ERROR)
                self.founds = False
                return
            dir_flash = self.getCurrentSelected()
            text = _("Flashing: ")
            cmd = "echo -e"
            if ret == "simulate":
                text += _("Simulate (no write)")
                cmd = "%s -n '%s'" % (ofgwrite_bin, dir_flash)
            elif ret == "standard":
                text += _("Standard (root and kernel)")
                if self.ForceMode:
                    cmd = "%s -f -r -k '%s' > /dev/null 2>&1 &" % (
                        ofgwrite_bin, dir_flash)
                else:
                    cmd = "%s -r -k '%s' > /dev/null 2>&1 &" % (ofgwrite_bin,
                                                                dir_flash)
            elif ret == "root":
                text += _("Only root")
                cmd = "%s -r '%s' > /dev/null 2>&1 &" % (ofgwrite_bin,
                                                         dir_flash)
            elif ret == "kernel":
                text += _("Only kernel")
                cmd = "%s -k '%s' > /dev/null 2>&1 &" % (ofgwrite_bin,
                                                         dir_flash)
            elif ret == "simulate2":
                text += _("Simulate second partition (no write)")
                cmd = "%s -kmtd3 -rmtd4 -n '%s'" % (ofgwrite_bin, dir_flash)
            elif ret == "standard2":
                text += _("Second partition (root and kernel)")
                cmd = "%s -kmtd3 -rmtd4 '%s' > /dev/null 2>&1 &" % (
                    ofgwrite_bin, dir_flash)
            elif ret == "rootfs2":
                text += _("Second partition (only root)")
                cmd = "%s -rmtd4 '%s' > /dev/null 2>&1 &" % (ofgwrite_bin,
                                                             dir_flash)
            elif ret == "kernel2":
                text += _("Second partition (only kernel)")
                cmd = "%s -kmtd3 '%s' > /dev/null 2>&1 &" % (ofgwrite_bin,
                                                             dir_flash)
            else:
                return
            message = "echo -e '\n"
            message += _('NOT found files for flashing!\n')
            message += "'"
            if ret == "simulate" or ret == "simulate2":
                if self.founds:
                    message = "echo -e '\n"
                    message += _('Show only found image and mtd partitions.\n')
                    message += "'"
            else:
                if self.founds:
                    message = "echo -e '\n"
                    message += _(
                        'ofgwrite will stop enigma2 now to run the flash.\n')
                    message += _(
                        'Your STB will freeze during the flashing process.\n')
                    message += _(
                        'Please: DO NOT reboot your STB and turn off the power.\n'
                    )
                    message += _(
                        'The image or kernel will be flashing and auto booted in few minutes.\n'
                    )
                    message += "'"
            self.session.open(Console, text, [message, cmd])

    def keyRed(self):
        self.close()

    def keyYellow(self):
        if self["key_yellow"].getText() == _("Unzip"):
            filename = self.filelist.getFilename()
            if filename and filename.endswith(".zip"):
                self.session.openWithCallback(
                    self.doUnzip, MessageBox,
                    _("Do you really want to unpack %s ?") % filename,
                    MessageBox.TYPE_YESNO)
        elif self["key_yellow"].getText() == _("Backup info"):
            self.session.open(MessageBox, "\n\n\n%s" % self.getBackupInfo(),
                              MessageBox.TYPE_INFO)

    def getBackupInfo(self):
        backup_dir = self.getCurrentSelected()
        backup_info = ""
        for line in open(backup_dir + VERSIONFILE, "r"):
            backup_info += line
        return backup_info

    def doUnzip(self, answer):
        if answer is True:
            dirname = self.filelist.getCurrentDirectory()
            filename = self.filelist.getFilename()
            if dirname and filename:
                try:
                    os.system('unzip -o %s%s -d %s' %
                              (dirname, filename, dirname))
                    self.filelist.refresh()
                except:
                    pass

    def confirmedDelete(self, answer):
        if answer is True:
            backup_dir = self.getCurrentSelected()
            cmdmessage = "echo -e 'Removing backup:   %s\n'" % os.path.basename(
                backup_dir.rstrip('/'))
            cmddelete = "rm -rf %s > /dev/null 2>&1" % backup_dir
            self.session.open(Console, _("Delete backup"),
                              [cmdmessage, cmddelete], self.filelist.refresh)

    def KeyBlue(self):
        if self["key_blue"].getText() == _("Delete"):
            self.session.openWithCallback(
                self.confirmedDelete, MessageBox,
                _("You are about to delete this backup:\n\n%s\nContinue?") %
                self.getBackupInfo(), MessageBox.TYPE_YESNO)
Example #8
0
class FileBrowser(Screen):
	title = _("File Browser")
	select = _("Select")

	skin = """
		<screen name="FileBrowser_Generic" position="center,center" size="600,600"  title="%s" >
			<widget name="green" position="10,5" size="200,40" pixmap="Default-HD/buttons/green.png" alphatest="on"/>
			<widget name="key_green" position="10,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" shadowColor="black" shadowOffset="-2,-2"/>

			<widget name="filelist" position="10,55" size="580,435" scrollbarMode="showOnDemand"/>
			<widget name="status" position="0,545" size="600,20" font="Regular;18" halign="left" foregroundColors="white,white,white" backgroundColors="background,#00DD00,#DD0000"/>
		</screen>""" % (title)

	def __init__(self, session, showDirectories=True, showFiles=True, showMountpoints=True, matchingPattern=None, useServiceRef=False, inhibitDirs=False, inhibitMounts=False, isTop=False, enableWrapAround=False, additionalExtensions=None, closeOnSelection=False):
		Screen.__init__(self, session)
		self.skinName = "FileBrowser_Generic"

		defaultDir = None  # TODO Fix / Config value
		self._closeOnSelection = closeOnSelection
		self._filelist = FileList(defaultDir, showDirectories=showDirectories, showFiles=showFiles, showMountpoints=showMountpoints, matchingPattern=matchingPattern, useServiceRef=useServiceRef, inhibitDirs=inhibitDirs, inhibitMounts=inhibitMounts, isTop=isTop, enableWrapAround=enableWrapAround, additionalExtensions=additionalExtensions)

		self["filelist"] = self._filelist
		self["status"] = MultiColorLabel("")

		self["key_green"] = Button(_("Add"))
		self["green"] = Pixmap()

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

	def _onShown(self):
		self.summaries.setText(self.title, 1)
		self._onSelectionChanged()
		self._filelist.onSelectionChanged.append(self._onSelectionChanged)

	def _onSelectionChanged(self):
		# Update LCD Stuff
		curDir = self._filelist.getCurrentDirectory()
		if curDir != None:
			self.summaries.setText(curDir , 2)
		else:
			self.summaries.setText("" , 2)

		text = None
		if self._filelist.canDescent():
			text = self._filelist.getFilename()
			if text != None:
				text = "./%s" % (text.split('/')[-2])
				self.summaries.setText(text, 3)
			else:
				self.summaries.setText("", 3)

	def createSummary(self):
		return Simple4LineLCDScreen

	def ok(self):
		if self._filelist.canDescent():
			self._filelist.descent()
		else:
			self.selectCurrent()

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

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

	def pageUp(self):
		self._filelist.pageUp()

	def pageDown(self):
		self._filelist.pageDown()

	def selectCurrent(self):
		if self._filelist.canDescent():
			dir = os_path.dirname(self._filelist.getFilename()) + "/"
			if self.selectDirectory(dir):
				self.setStatus(dir)
			else:
				self.setStatus(dir, True)
		else:
			file = self._filelist.getFilename()
			if self.selectFile(self._filelist.getServiceRef()):
				self.setStatus(file)
			else:
				self.setStatus(file, True)

	def setStatus(self, file, error=False):
		if error:
			self["status"].setText(_("ERROR: Cannot add '%s'") % file)
			self["status"].setForegroundColorNum(2)
			self["status"].setBackgroundColorNum(2)
		else:
			self["status"].setText(_("Added '%s'") % file)
			self["status"].setForegroundColorNum(1)
			self["status"].setBackgroundColorNum(1)

	def selectDirectory(self, dir):
		return self.selectFile(dir)

	def selectFile(self, file):
		if file:
			if self._closeOnSelection:
				self.close(file)
				return True

		return False
class EVOMC_PictureViewer(Screen, HelpableScreen):
    def __init__(self, session):
        Screen.__init__(self, session)
        HelpableScreen.__init__(self)

        # Show Background MVI
        #system("/usr/bin/showiframe /usr/lib/enigma2/python/Plugins/Extensions/EVOMediaCenter/icons/background.mvi &")

        self["key_red"] = Button("Favorites")
        self["key_green"] = Button("Slide Show")
        self["key_yellow"] = Button("Thumb View")
        self["key_blue"] = Button(_("Settings"))

        self["currentfolder"] = Label("")
        self["currentfavname"] = Label("")
        self.curfavfolder = -1

        self["actions"] = HelpableActionMap(
            self,
            "EVOMC_PictureViewerActions",
            {
                "ok": (self.KeyOk, "Show Picture"),
                #				"cancel": (self.Exit, "Exit Picture Viewer"),
                "left": (self.leftUp, "List Top"),
                "right": (self.rightDown, "List Bottom"),
                "up": (self.up, "List up"),
                "down": (self.down, "List down"),
                "menu": (self.KeyMenu, "File / Folder Options"),
                "info": (self.StartExif, "Show File Info"),
                "nextBouquet": (self.NextFavFolder, "Next Favorite Folder"),
                "prevBouquet":
                (self.PrevFavFolder, "Previous Favorite Folder"),
                "red": (self.FavoriteFolders, "Favorite Folders"),
                "green": (self.startslideshow, "Start Slideshow"),
                "yellow": (self.StartThumb, "Thumb View"),
                "blue": (self.Settings, "Settings"),
            },
            -2)

        self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions", {
            "cancel": (self.Exit, "Exit Picture Viewer"),
        }, -2)

        self.aspect = getAspect()
        currDir = config.plugins.EVOMC_pp.lastDir.value
        if not pathExists(currDir):
            currDir = "/"

        self["currentfolder"].setText(str(currDir))

        self.filelist = FileList(
            currDir, matchingPattern="(?i)^.*\.(jpeg|jpg|jpe|png|bmp)")
        self["filelist"] = self.filelist
        self["thumbnail"] = Pixmap()
        evfd.getInstance().vfd_write_string("EVO-PICVIEWER")
        self.ThumbTimer = eTimer()
        self.ThumbTimer.callback.append(self.showThumb)
        self.ThumbTimer.start(500, True)

        self.picload = ePicLoad()
        #self.picload.PictureData.get().append(self.showPic)

    def startslideshow(self):
        self.session.openWithCallback(self.returnVal, EVOMC_PicView,
                                      self.filelist.getFileList(),
                                      self.filelist.getSelectionIndex(),
                                      self.filelist.getCurrentDirectory(),
                                      True)

    def up(self):
        self["filelist"].up()
        self.ThumbTimer.start(500, True)

    def down(self):
        self["filelist"].down()
        self.ThumbTimer.start(500, True)

    def leftUp(self):
        self["filelist"].pageUp()
        self.ThumbTimer.start(500, True)

    def rightDown(self):
        self["filelist"].pageDown()
        self.ThumbTimer.start(500, True)

    def NextFavFolder(self):
        if self.curfavfolder + 1 < config.plugins.EVOMC_favorites.foldercount.value:
            self.curfavfolder += 1
            self.favname = config.plugins.EVOMC_favorites.folders[
                self.curfavfolder].name.value
            self.folder = config.plugins.EVOMC_favorites.folders[
                self.curfavfolder].basedir.value
            self["currentfolder"].setText(("%s") % (self.folder))
            self["currentfavname"].setText(("%s") % (self.favname))
            if pathExists(self.folder) == True:
                self["filelist"].changeDir(self.folder)
        else:
            return

    def PrevFavFolder(self):
        if self.curfavfolder <= 0:
            return
        else:
            self.curfavfolder -= 1
            self.favname = config.plugins.EVOMC_favorites.folders[
                self.curfavfolder].name.value
            self.folder = config.plugins.EVOMC_favorites.folders[
                self.curfavfolder].basedir.value
            self["currentfolder"].setText(("%s") % (self.folder))
            self["currentfavname"].setText(("%s") % (self.favname))
            if pathExists(self.folder) == True:
                self["filelist"].changeDir(self.folder)

    def showPic(self, picInfo=""):
        ptr = self.picload.getData()
        if ptr != None:
            self["thumbnail"].instance.setPixmap(ptr.__deref__())
            self["thumbnail"].show()

    def showThumb(self):
        return
        if not self.filelist.canDescent():
            if self.picload.getThumbnail(self.filelist.getCurrentDirectory() +
                                         self.filelist.getFilename()) == 1:
                ptr = self.picload.getData()
            else:
                ptr = None

            #ptr = loadPic(self.filelist.getCurrentDirectory() + self.filelist.getFilename(), 180, 160, self.aspect, int(config.plugins.EVOMC_pp.resize.value), 0, 0, cachefile)
            if ptr != None:
                self["thumbnail"].instance.setPixmap(ptr.__deref__())
                self["thumbnail"].show()
        else:
            self["thumbnail"].hide()

    def KeyOk(self):
        if self.filelist.canDescent():
            self.filelist.descent()
        else:
            self.session.openWithCallback(self.returnVal, EVOMC_PicView,
                                          self.filelist.getFileList(),
                                          self.filelist.getSelectionIndex(),
                                          self.filelist.getCurrentDirectory(),
                                          False)

    def KeyMenu(self):
        self.ThumbTimer.stop()
        if self["filelist"].canDescent():
            if self.filelist.getCurrent()[0][1]:
                self.currentDirectory = self.filelist.getCurrent()[0][0]
                foldername = self.currentDirectory.split('/')
                foldername = foldername[-2]
                self.session.open(EVOMC_FolderOptions, self.currentDirectory,
                                  foldername)

    def StartThumb(self):
        self.session.openWithCallback(self.returnVal, EVOMC_PicThumbViewer,
                                      self.filelist.getFileList(),
                                      self.filelist.getSelectionIndex(),
                                      self.filelist.getCurrentDirectory())

    def JumpToFolder(self, jumpto=None):
        if jumpto is None:
            return
        else:
            self["filelist"].changeDir(jumpto)
            self["currentfolder"].setText(("%s") % (jumpto))

    def FavoriteFolders(self):
        self.session.openWithCallback(self.JumpToFolder, EVOMC_FavoriteFolders)

    def returnVal(self, val=0):
        if val > 0:
            for x in self.filelist.getFileList():
                if x[0][1] == True:
                    val += 1
            self.filelist.moveToIndex(val)

    def StartExif(self):
        if not self.filelist.canDescent():
            #self.session.open(Pic_Exif, self.filelist.getCurrentDirectory() + self.filelist.getFilename(), self.filelist.getFilename())
            #self.session.open(Pic_Exif, self.picload.getInfo(self.filelist.getSelectionIndex()))
            self.session.open(MessageBox, "Oh no, bugged in this version :(",
                              MessageBox.TYPE_ERROR)

    def Settings(self):
        self.session.open(EVOMC_PicSetup)

    def Exit(self):
        if self.filelist.getCurrentDirectory() is None:
            config.plugins.EVOMC_pp.lastDir.value = "/"
        else:
            config.plugins.EVOMC_pp.lastDir.value = self.filelist.getCurrentDirectory(
            )

        config.plugins.EVOMC_pp.save()
        self.close()
class EVOMC_PictureViewer(Screen, HelpableScreen):
	def __init__(self, session):
		Screen.__init__(self, session)
		HelpableScreen.__init__(self)
		
		# Show Background MVI
		#system("/usr/bin/showiframe /usr/lib/enigma2/python/Plugins/Extensions/EVOMediaCenter/icons/background.mvi &")
		
		self["key_red"] = Button("Favorites")
		self["key_green"] = Button("Slide Show")
		self["key_yellow"] = Button("Thumb View")
		self["key_blue"] = Button(_("Settings"))

		self["currentfolder"] = Label("")
		self["currentfavname"] = Label("")
		self.curfavfolder = -1

		self["actions"] = HelpableActionMap(self, "EVOMC_PictureViewerActions", 
			{
				"ok": (self.KeyOk, "Show Picture"),
#				"cancel": (self.Exit, "Exit Picture Viewer"),
				"left": (self.leftUp, "List Top"),
				"right": (self.rightDown, "List Bottom"),
				"up": (self.up, "List up"),
				"down": (self.down, "List down"),
				"menu": (self.KeyMenu, "File / Folder Options"),
				"info": (self.StartExif, "Show File Info"),
				"nextBouquet": (self.NextFavFolder, "Next Favorite Folder"),
				"prevBouquet": (self.PrevFavFolder, "Previous Favorite Folder"),
				"red": (self.FavoriteFolders, "Favorite Folders"),
				"green": (self.startslideshow, "Start Slideshow"),
				"yellow": (self.StartThumb, "Thumb View"),
				"blue": (self.Settings, "Settings"),
			}, -2)
			
		self["OkCancelActions"] = HelpableActionMap(self, "OkCancelActions", 
			{
				"cancel": (self.Exit, "Exit Picture Viewer"),
			}, -2)
		
		self.aspect = getAspect()
		currDir = config.plugins.EVOMC_pp.lastDir.value
		if not pathExists(currDir):
			currDir = "/"

		self["currentfolder"].setText(str(currDir))

		self.filelist = FileList(currDir, matchingPattern = "(?i)^.*\.(jpeg|jpg|jpe|png|bmp)")
		self["filelist"] = self.filelist
		self["thumbnail"] = Pixmap()
		evfd.getInstance().vfd_write_string("EVO-PICVIEWER")
		self.ThumbTimer = eTimer()
		self.ThumbTimer.callback.append(self.showThumb)
		self.ThumbTimer.start(500, True)

		self.picload = ePicLoad()
		#self.picload.PictureData.get().append(self.showPic)
		
	def startslideshow(self):
		self.session.openWithCallback(self.returnVal , EVOMC_PicView, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory(), True)

	def up(self):
		self["filelist"].up()
		self.ThumbTimer.start(500, True)

	def down(self):
		self["filelist"].down()
		self.ThumbTimer.start(500, True)
		
	def leftUp(self):
		self["filelist"].pageUp()
		self.ThumbTimer.start(500, True)
		
	def rightDown(self):
		self["filelist"].pageDown()
		self.ThumbTimer.start(500, True)

	def NextFavFolder(self):
		if self.curfavfolder + 1 < config.plugins.EVOMC_favorites.foldercount.value:
			self.curfavfolder += 1
			self.favname = config.plugins.EVOMC_favorites.folders[self.curfavfolder].name.value
			self.folder = config.plugins.EVOMC_favorites.folders[self.curfavfolder].basedir.value
			self["currentfolder"].setText(("%s") % (self.folder))
			self["currentfavname"].setText(("%s") % (self.favname))
			if pathExists(self.folder) == True:
				self["filelist"].changeDir(self.folder)
		else:
			return
			
	def PrevFavFolder(self):
		if self.curfavfolder <= 0:
			return
		else:
			self.curfavfolder -= 1
			self.favname = config.plugins.EVOMC_favorites.folders[self.curfavfolder].name.value
			self.folder = config.plugins.EVOMC_favorites.folders[self.curfavfolder].basedir.value
			self["currentfolder"].setText(("%s") % (self.folder))
			self["currentfavname"].setText(("%s") % (self.favname))
			if pathExists(self.folder) == True:
				self["filelist"].changeDir(self.folder)

	def showPic(self, picInfo=""):
		ptr = self.picload.getData()
		if ptr != None:
			self["thumbnail"].instance.setPixmap(ptr.__deref__())
			self["thumbnail"].show()
			
	def showThumb(self):
		return
		if not self.filelist.canDescent():
			if self.picload.getThumbnail(self.filelist.getCurrentDirectory() + self.filelist.getFilename()) == 1:
				ptr = self.picload.getData()
			else:
				ptr = None
			
			#ptr = loadPic(self.filelist.getCurrentDirectory() + self.filelist.getFilename(), 180, 160, self.aspect, int(config.plugins.EVOMC_pp.resize.value), 0, 0, cachefile)
			if ptr != None:
				self["thumbnail"].instance.setPixmap(ptr.__deref__())
				self["thumbnail"].show()
		else:
			self["thumbnail"].hide()

	def KeyOk(self):
		if self.filelist.canDescent():
			self.filelist.descent()
		else:
			self.session.openWithCallback(self.returnVal, EVOMC_PicView, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory(), False)

	def KeyMenu(self):
		self.ThumbTimer.stop()
		if self["filelist"].canDescent():
			if self.filelist.getCurrent()[0][1]:
				self.currentDirectory = self.filelist.getCurrent()[0][0]
				foldername = self.currentDirectory.split('/')
				foldername = foldername[-2]
				self.session.open(EVOMC_FolderOptions,self.currentDirectory, foldername)
	
	def StartThumb(self):
		self.session.openWithCallback(self.returnVal, EVOMC_PicThumbViewer, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory())

	def JumpToFolder(self, jumpto = None):
		if jumpto is None:
			return
		else:
			self["filelist"].changeDir(jumpto)
			self["currentfolder"].setText(("%s") % (jumpto))
	
	def FavoriteFolders(self):
		self.session.openWithCallback(self.JumpToFolder, EVOMC_FavoriteFolders)

	def returnVal(self, val=0):
		if val > 0:
			for x in self.filelist.getFileList():
				if x[0][1] == True:
					val += 1
			self.filelist.moveToIndex(val)

	def StartExif(self):
		if not self.filelist.canDescent():
			#self.session.open(Pic_Exif, self.filelist.getCurrentDirectory() + self.filelist.getFilename(), self.filelist.getFilename())
			#self.session.open(Pic_Exif, self.picload.getInfo(self.filelist.getSelectionIndex()))
			self.session.open(MessageBox, "Oh no, bugged in this version :(", MessageBox.TYPE_ERROR)

	def Settings(self):
		self.session.open(EVOMC_PicSetup)
	
	def Exit(self):
		if self.filelist.getCurrentDirectory() is None:
			config.plugins.EVOMC_pp.lastDir.value = "/"
		else:
			config.plugins.EVOMC_pp.lastDir.value = self.filelist.getCurrentDirectory()

		config.plugins.EVOMC_pp.save()
		self.close()
class MC_PictureViewer(Screen, HelpableScreen):
	def __init__(self, session):
		Screen.__init__(self, session)
		HelpableScreen.__init__(self)
		self["key_green"] = Button("Slide Show")
		self["key_yellow"] = Button("Thumb View")
		self["currentfolder"] = Label("")
		self["currentfavname"] = Label("")
		self["actions"] = HelpableActionMap(self, "MC_PictureViewerActions", 
			{
				"ok": (self.KeyOk, "Show Picture"),
				"cancel": (self.Exit, "Exit Picture Viewer"),
				"left": (self.leftUp, "List Top"),
				"right": (self.rightDown, "List Bottom"),
				"up": (self.up, "List up"),
				"down": (self.down, "List down"),
				"info": (self.StartExif, "Show File Info"),
				"green": (self.startslideshow, "Start Slideshow"),
				"yellow": (self.StartThumb, "Thumb View"),
				"blue": (self.Settings, "Settings"),
			}, -2)

		self.aspect = getAspect()
		currDir = config.plugins.mc_pp.lastDir.value
		if not pathExists(currDir):
			currDir = "/"
		self["currentfolder"].setText(str(currDir))
		self.filelist = []
		self["filelist"] = []
		inhibitDirs = ["/bin", "/boot", "/dev", "/dev.static", "/etc", "/lib" , "/proc", "/ram", "/root" , "/sbin", "/sys", "/tmp", "/usr", "/var"]
		self.filelist = FileList(currDir, showDirectories = True, showFiles = True, showMountpoints = True, isTop = False, matchingPattern = "(?i)^.*\.(jpeg|jpg|jpe|png|bmp)", inhibitDirs = inhibitDirs)
		self["filelist"] = self.filelist
		self["filelist"].show()
		self["thumbnail"] = Pixmap()
		self.ThumbTimer = eTimer()
		self.ThumbTimer.callback.append(self.showThumb)
		self.ThumbTimer.start(500, True)

		self.picload = ePicLoad()
		#self.picload.PictureData.get().append(self.showPic)

	def startslideshow(self):
		self.session.openWithCallback(self.returnVal , MC_PicView, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory(), True)

	def up(self):
		self["filelist"].up()
		self.ThumbTimer.start(500, True)
	def down(self):
		self["filelist"].down()
		self.ThumbTimer.start(500, True)
	def leftUp(self):
		self["filelist"].pageUp()
		self.ThumbTimer.start(500, True)
	def rightDown(self):
		self["filelist"].pageDown()
		self.ThumbTimer.start(500, True)
	def showPic(self, picInfo=""):
		ptr = self.picload.getData()
		if ptr != None:
			self["thumbnail"].instance.setPixmap(ptr.__deref__())
			self["thumbnail"].show()

	def showThumb(self):
		return
		if not self.filelist.canDescent():
			if self.picload.getThumbnail(self.filelist.getCurrentDirectory() + self.filelist.getFilename()) == 1:
				ptr = self.picload.getData()
			else:
				ptr = None
			
			#ptr = loadPic(self.filelist.getCurrentDirectory() + self.filelist.getFilename(), 180, 160, self.aspect, int(config.plugins.mc_pp.resize.value), 0, 0, cachefile)
			if ptr != None:
				self["thumbnail"].instance.setPixmap(ptr.__deref__())
				self["thumbnail"].show()
		else:
			self["thumbnail"].hide()

	def KeyOk(self):
		if self.filelist.canDescent():
			self.filelist.descent()
		else:
			self.session.openWithCallback(self.returnVal, MC_PicView, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory(), False)
	def StartThumb(self):
		self.session.openWithCallback(self.returnVal, MC_PicThumbViewer, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory())

	def JumpToFolder(self, jumpto = None):
		if jumpto is None:
			return
		else:
			self["filelist"].changeDir(jumpto)
			self["currentfolder"].setText(("%s") % (jumpto))
	def returnVal(self, val=0):
		if val > 0:
			for x in self.filelist.getFileList():
				if x[0][1] == True:
					val += 1
			self.filelist.moveToIndex(val)

	def StartExif(self):
		if not self.filelist.canDescent():
			#self.session.open(Pic_Exif, self.filelist.getCurrentDirectory() + self.filelist.getFilename(), self.filelist.getFilename())
			#self.session.open(Pic_Exif, self.picload.getInfo(self.filelist.getSelectionIndex()))
			self.session.open(MessageBox, "Oh no, bugged in this version :(", MessageBox.TYPE_ERROR)

	def Settings(self):
		self.session.open(MC_PicSetup)
	def Exit(self):
		if self.filelist.getCurrentDirectory() is None:
			config.plugins.mc_pp.lastDir.value = "/"
		else:
			config.plugins.mc_pp.lastDir.value = self.filelist.getCurrentDirectory()
		config.plugins.mc_pp.save()
		self.close()
Example #12
0
class picshow(Screen):
	skin = """
		<screen name="picshow" position="center,center" size="560,440" title="PicturePlayer" >
			<ePixmap pixmap="buttons/red.png" position="0,0" size="140,40" alphatest="on" />
			<ePixmap pixmap="buttons/green.png" position="140,0" size="140,40" alphatest="on" />
			<ePixmap pixmap="buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
			<ePixmap pixmap="buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
			<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
			<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
			<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
			<widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
			<widget source="label" render="Label" position="5,55" size="350,140" font="Regular;19" backgroundColor="#25062748" transparent="1"  />
			<widget name="thn" position="360,40" size="180,160" alphatest="on" />
			<widget name="filelist" position="5,205" zPosition="2" size="550,230" scrollbarMode="showOnDemand" />
		</screen>"""

	def __init__(self, session):
		Screen.__init__(self, session)

		self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions"],
		{
			"cancel": self.KeyExit,
			"red": self.KeyExit,
			"green": self.KeyGreen,
			"yellow": self.KeyYellow,
			"blue": self.KeyBlue,
			"ok": self.KeyOk
		}, -1)

		self["key_red"] = StaticText(_("Close"))
		self["key_green"] = StaticText(_("Thumbnails"))
		self["key_yellow"] = StaticText("")
		self["key_blue"] = StaticText(_("Setup"))
		self["label"] = StaticText("")
		self["thn"] = Pixmap()

		currDir = config.pic.lastDir.value
		if not pathExists(currDir):
			currDir = "/"

		self.filelist = FileList(currDir, matchingPattern = "(?i)^.*\.(jpeg|jpg|jpe|png|bmp|gif)")
		self["filelist"] = self.filelist
		self["filelist"].onSelectionChanged.append(self.selectionChanged)

		self.ThumbTimer = eTimer()
		self.ThumbTimer.callback.append(self.showThumb)

		self.picload = ePicLoad()
		self.picload.PictureData.get().append(self.showPic)

		self.onLayoutFinish.append(self.setConf)

	def showPic(self, picInfo=""):
		ptr = self.picload.getData()
		if ptr != None:
			self["thn"].instance.setPixmap(ptr.__deref__())
			self["thn"].show()

		text = picInfo.split('\n',1)
		self["label"].setText(text[1])
		self["key_yellow"].setText(_("Exif"))

	def showThumb(self):
		if not self.filelist.canDescent():
			if self.filelist.getCurrentDirectory() and self.filelist.getFilename():
				if self.picload.getThumbnail(self.filelist.getCurrentDirectory() + self.filelist.getFilename()) == 1:
					self.ThumbTimer.start(500, True)

	def selectionChanged(self):
		if not self.filelist.canDescent():
			self.ThumbTimer.start(500, True)
		else:
			self["label"].setText("")
			self["thn"].hide()
			self["key_yellow"].setText("")

	def KeyGreen(self):
		#if not self.filelist.canDescent():
		self.session.openWithCallback(self.callbackView, Pic_Thumb, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory())

	def KeyYellow(self):
		if not self.filelist.canDescent():
			self.session.open(Pic_Exif, self.picload.getInfo(self.filelist.getCurrentDirectory() + self.filelist.getFilename()))

	def KeyBlue(self):
		self.session.openWithCallback(self.setConf ,Pic_Setup)

	def KeyOk(self):
		if self.filelist.canDescent():
			self.filelist.descent()
		else:
			self.session.openWithCallback(self.callbackView, Pic_Full_View, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory())

	def setConf(self):
		self.setTitle(_("PicturePlayer"))
		sc = getScale()
		#0=Width 1=Height 2=Aspect 3=use_cache 4=resize_type 5=Background(#AARRGGBB)
		self.picload.setPara((self["thn"].instance.size().width(), self["thn"].instance.size().height(), sc[0], sc[1], config.pic.cache.value, int(config.pic.resize.value), "#00000000"))

	def callbackView(self, val=0):
		if val > 0:
			self.filelist.moveToIndex(val)

	def KeyExit(self):
		del self.picload

		if self.filelist.getCurrentDirectory() is None:
			config.pic.lastDir.value = "/"
		else:
			config.pic.lastDir.value = self.filelist.getCurrentDirectory()

		config.pic.save()
		self.close()
Example #13
0
class FlashImageConfig(Screen):
	def __init__(self, session, curdir, matchingPattern=None):
		try:
			sz_w = getDesktop(0).size().width()
		except:
			sz_w = 720
		if sz_w == 1920:
			self.skin = skinflashfullhd
		elif sz_w >= 1280:
			self.skin = skinflashhd
		else:
			self.skin = skinflashsd

		Screen.__init__(self, session)
		self["Title"].setText(_("Select the folder with backup"))
		self["key_red"] = StaticText(_("Close"))
		self["key_green"] = StaticText("")
		self["key_yellow"] = StaticText("")
		self["key_blue"] = StaticText("")
		self["curdir"] = StaticText(_("current:  %s")%(curdir or ''))
		self.founds = False
		self.dualboot = self.dualBoot()
		self.filelist = FileList(curdir, matchingPattern=matchingPattern, enableWrapAround=True)
		self.filelist.onSelectionChanged.append(self.__selChanged)
		self["filelist"] = self.filelist

		self["FilelistActions"] = ActionMap(["SetupActions", "ColorActions"],
			{
				"green": self.keyGreen,
				"red": self.keyRed,
				"yellow": self.keyYellow,
				"blue": self.KeyBlue,
				"ok": self.keyOk,
				"cancel": self.keyRed
			})
		self.onLayoutFinish.append(self.__layoutFinished)

	def __layoutFinished(self):
		pass

	def dualBoot(self):
		if os.path.exists("/proc/stb/info/boxtype"):
			try:
				fd = open("/proc/stb/info/boxtype")
				model = fd.read().strip()
				fd.close()
				if model == "et8500":
					rootfs2 = False
					kernel2 = False
					f = open("/proc/mtd")
					l = f.readlines()
					for x in l:
						if 'rootfs2' in x:
							rootfs2 = True
						if 'kernel2' in x:
							kernel2 = True
					f.close()
					if rootfs2 and kernel2:
						return True
			except:
				pass
		return False

	def getCurrentSelected(self):
		dirname = self.filelist.getCurrentDirectory()
		filename = self.filelist.getFilename()
		if not filename and not dirname:
			cur = ''
		elif not filename:
			cur = dirname
		elif not dirname:
			cur = filename
		else:
			if not self.filelist.canDescent() or len(filename) <= len(dirname):
				cur = dirname
			else:
				cur = filename
		return cur or ''

	def __selChanged(self):
		self["key_yellow"].setText("")
		self["key_green"].setText("")
		self["key_blue"].setText("")
		self["curdir"].setText(_("current:  %s")%(self.getCurrentSelected()))
		file_name = self.getCurrentSelected()
		try:
			if not self.filelist.canDescent() and file_name != '' and file_name != '/':
				filename = self.filelist.getFilename()
				if filename and filename.endswith(".zip"):
					self["key_yellow"].setText(_("Unzip"))
			elif self.filelist.canDescent() and file_name != '' and file_name != '/':
				self["key_green"].setText(_("Run flash"))
				if os.path.isfile(file_name + LOGFILE) and os.path.isfile(file_name + VERSIONFILE):
					self["key_yellow"].setText(_("Backup info"))
					self["key_blue"].setText(_("Delete"))
		except:
			pass

	def keyOk(self):
		if self.filelist.canDescent():
			self.filelist.descent()

	def confirmedWarning(self, result):
		if result:
			self.founds = False
			self.showparameterlist()

	def keyGreen(self):
		if self["key_green"].getText() == _("Run flash"):
			dirname = self.filelist.getCurrentDirectory()
			if dirname:
				warning_text = "\n"
				if self.dualboot:
					warning_text += _("\nYou are using dual multiboot!")
				self.session.openWithCallback(lambda r: self.confirmedWarning(r), MessageBox, _("Warning!\nUse at your own risk! Make always a backup before use!\nDon't use it if you use multiple ubi volumes in ubi layer!")  + warning_text, MessageBox.TYPE_INFO)

	def showparameterlist(self):
		if self["key_green"].getText() == _("Run flash"):
			dirname = self.getCurrentSelected()
			if dirname:
				backup_files = []
				no_backup_files = []
				text = _("Select parameter for start flash!\n")
				text += _('For flashing your receiver files are needed:\n')
				if os.path.exists("/proc/stb/info/hwmodel"):
					f = open("/proc/stb/info/hwmodel")
					model = f.read().strip()
					f.close()
					if model in ["fusionhd", "fusionhdse"]:
						backup_files = ["oe_kernel.bin", "oe_rootfs.bin"]
						text += "oe_kernel.bin, oe_rootfs.bin"
				elif os.path.exists("/proc/stb/info/boxtype"):
					f = open("/proc/stb/info/boxtype")
					model = f.read().strip()
					f.close()
					if model in ["hd51"]:
						backup_files = [("kernel1.bin"), ("rootfs.tar.bz2")]
						no_backup_files = ["kernel_cfe_auto.bin", "kernel.bin", "rootfs.bin", "root_cfe_auto.jffs2", "root_cfe_auto.bin"]
						text += 'kernel1.bin, rootfs.tar.bz2'
					else:
						backup_files = [("kernel.bin"), ("rootfs.bin")]
						no_backup_files = ["kernel_cfe_auto.bin", "root_cfe_auto.jffs2", "root_cfe_auto.bin"]
						text += 'kernel.bin, rootfs.bin'
				elif os.path.exists("/proc/stb/info/vumodel"):
					f = open("/proc/stb/info/vumodel")
					model = f.read().strip()
					f.close()
					if model in ["solo4k", "uno4k", "ultimo4k"]:
						backup_files = ["kernel_auto.bin", "rootfs.tar.bz2"]
						no_backup_files = ["kernel.bin", "kernel_cfe_auto.bin", "root_cfe_auto.bin" "root_cfe_auto.jffs2", "rootfs.bin"]
						text += 'kernel_auto.bin, rootfs.tar.bz2'
					elif model in ["duo2", "solose", "solo2", "zero"]:
						backup_files = ["kernel_cfe_auto.bin", "root_cfe_auto.bin"]
						no_backup_files = ["kernel.bin", "kernel_auto.bin", "root_cfe_auto.jffs2", "rootfs.bin", "rootfs.tar.bz2"]
						text += 'kernel_cfe_auto.bin, root_cfe_auto.bin'
					else:
						backup_files = ["kernel_cfe_auto.bin", "root_cfe_auto.jffs2"]
						no_backup_files = ["kernel.bin", "kernel_auto.bin", "root_cfe_auto.bin", "rootfs.bin", "rootfs.tar.bz2"]
						text += 'kernel_cfe_auto.bin, root_cfe_auto.jffs2'
				try:
					self.founds = False
					text += _('\nThe found files:')
					for name in os.listdir(dirname):
						if name in backup_files:
							text += _("  %s (maybe ok)") % name
							self.founds = True
						if name in no_backup_files:
							text += _("  %s (maybe error)") % name
							self.founds = True
					if not self.founds:
						text += _(' nothing!')
				except:
					pass
				if self.founds:
					open_list = [
						(_("Simulate (no write)"), "simulate"),
						(_("Standard (root and kernel)"), "standard"),
						(_("Only root"), "root"),
						(_("Only kernel"), "kernel"),
					]
					open_list2 = [
						(_("Simulate second partition (no write)"), "simulate2"),
						(_("Second partition (root and kernel)"), "standard2"),
						(_("Second partition (only root)"), "root2"),
						(_("Second partition (only kernel)"), "kernel2"),
					]
					if self.dualboot:
						open_list += open_list2
				else:
					open_list = [
						(_("Exit"), "exit"),
					]
				self.session.openWithCallback(self.Callbackflashing, MessageBox, text, simple = True, list = open_list)

	def Callbackflashing(self, ret):
		if ret:
			if ret == "exit":
				self.close()
				return
			if self.session.nav.RecordTimer.isRecording():
				self.session.open(MessageBox, _("A recording is currently running. Please stop the recording before trying to start a flashing."), MessageBox.TYPE_ERROR)
				self.founds = False
				return
			dir_flash = self.getCurrentSelected()
			text = _("Flashing: ")
			cmd = "echo -e"
			if ret == "simulate":
				text += _("Simulate (no write)")
				cmd = "%s -n '%s'" % (ofgwrite_bin, dir_flash)
			elif ret == "standard":
				text += _("Standard (root and kernel)")
				cmd = "%s -r -k '%s' > /dev/null 2>&1 &" % (ofgwrite_bin, dir_flash)
			elif ret == "root":
				text += _("Only root")
				cmd = "%s -r '%s' > /dev/null 2>&1 &" % (ofgwrite_bin, dir_flash)
			elif ret == "kernel":
				text += _("Only kernel")
				cmd = "%s -k '%s' > /dev/null 2>&1 &" % (ofgwrite_bin, dir_flash)
			elif ret == "simulate2":
				text += _("Simulate second partition (no write)")
				cmd = "%s -kmtd3 -rmtd4 -n '%s'" % (ofgwrite_bin, dir_flash)
			elif ret == "standard2":
				text += _("Second partition (root and kernel)")
				cmd = "%s -kmtd3 -rmtd4 '%s' > /dev/null 2>&1 &" % (ofgwrite_bin, dir_flash)
			elif ret == "root2":
				text += _("Second partition (only root)")
				cmd = "%s -rmtd4 '%s' > /dev/null 2>&1 &" % (ofgwrite_bin, dir_flash)
			elif ret == "kernel2":
				text += _("Second partition (only kernel)")
				cmd = "%s -kmtd3 '%s' > /dev/null 2>&1 &" % (ofgwrite_bin, dir_flash)
			else:
				return
			message = "echo -e '\n"
			message += _('NOT found files for flashing!\n')
			message += "'"
			if ret == "simulate" or ret == "simulate2":
				if self.founds:
					message = "echo -e '\n"
					message += _('Show only found image and mtd partitions.\n')
					message += "'"
			else:
				if self.founds:
					message = "echo -e '\n"
					message += _('ofgwrite will stop enigma2 now to run the flash.\n')
					message += _('Your STB will freeze during the flashing process.\n')
					message += _('Please: DO NOT reboot your STB and turn off the power.\n')
					message += _('The image or kernel will be flashing and auto booted in few minutes.\n')
					message += "'"
			try:
				if os.path.exists(ofgwrite_bin):
					os.chmod(ofgwrite_bin, 0755)
			except:
				pass
			self.session.open(Console, text,[message, cmd])

	def keyRed(self):
		self.close()

	def keyYellow(self):
		if self["key_yellow"].getText() == _("Unzip"):
			filename = self.filelist.getFilename()
			if filename and filename.endswith(".zip"):
				self.session.openWithCallback(self.doUnzip, MessageBox, _("Do you really want to unpack %s ?") % filename, MessageBox.TYPE_YESNO)
		elif self["key_yellow"].getText() == _("Backup info"):
			self.session.open(MessageBox, "\n\n\n%s" % self.getBackupInfo(), MessageBox.TYPE_INFO)

	def getBackupInfo(self):
		backup_dir = self.getCurrentSelected()
		backup_info = ""
		for line in open(backup_dir + VERSIONFILE, "r"):
			backup_info += line
		return backup_info

	def doUnzip(self, answer):
		if answer is True:
			dirname = self.filelist.getCurrentDirectory()
			filename = self.filelist.getFilename()
			if dirname and filename:
				try:
					os.system('unzip -o %s%s -d %s'%(dirname,filename,dirname))
					self.filelist.refresh()
				except:
					pass

	def confirmedDelete(self, answer):
		if answer is True:
			backup_dir = self.getCurrentSelected()
			cmdmessage = "echo -e 'Removing backup:   %s\n'" % os.path.basename(backup_dir.rstrip('/'))
			cmddelete = "rm -rf %s > /dev/null 2>&1" % backup_dir
			self.session.open(Console, _("Delete backup"), [cmdmessage, cmddelete], self.filelist.refresh)

	def KeyBlue(self):
		if self["key_blue"].getText() == _("Delete"):
			self.session.openWithCallback(self.confirmedDelete, MessageBox, _("You are about to delete this backup:\n\n%s\nContinue?") % self.getBackupInfo(), MessageBox.TYPE_YESNO)
Example #14
0
class EL_Screen_PathSelector(Screen):

	#===========================================================================
	# 
	#===========================================================================
	def __init__(self, session, initDir, myType, title):
		Screen.__init__(self, session)

		self.guiElements = getGuiElements()

		self.myType = myType
		self.title = title

		if not os.path.exists(initDir):
			initDir = "/etc/"
		
		self.filelist = FileList("/dev/", showDirectories = True, showFiles = True, showMountpoints = True, isTop = False, matchingPattern = "")
		self["filelist"] = self.filelist

		#self["filelist"]  = FileList(initDir, showDirectories = True, showFiles = True, showMountpoints = False, isTop = True, matchingPattern = "^.*\.(conf|config)")
		self["filelist"].changeDir(initDir.rsplit('/', 1)[0] + "/", select = initDir.rsplit('/', 1)[1])
		self["help"] = Label()
		self["help"].setText(initDir)
		self["actions"] = ActionMap(["WizardActions", "DirectionActions", "ColorActions", "EPGSelectActions"],
		{
			"back": self.cancel,
			"left": self.left,
			"right": self.right,
			"up": self.up,
			"down": self.down,
			"ok": self.ok,
			"green": self.green,
			"red": self.cancel
			
		}, -1)

		self["btn_red"]			= Pixmap()
		self["btn_redText"]		= Label()

		self["btn_green"]		= Pixmap()
		self["btn_greenText"]   = Label()

		self.onLayoutFinish.append(self.finishLayout)

	#===========================================================================
	#
	#===========================================================================
	def finishLayout(self):
		self["btn_red"].instance.setPixmapFromFile(self.guiElements["key_red"])
		self["btn_redText"].setText(_("Cancel"))

		self["btn_green"].instance.setPixmapFromFile(self.guiElements["key_green"])
		self["btn_greenText"].setText(_("Ok"))

		self.setTitle(_(self.title))

	#===========================================================================
	# 
	#===========================================================================
	def cancel(self):
		self.close(None, self.myType)
		
	#===========================================================================
	# 
	#===========================================================================
	def green(self):
		self.close(str(self["filelist"].getCurrentDirectory()) + str(self["filelist"].getSelection()[0]), self.myType)

	#===========================================================================
	# 
	#===========================================================================
	def up(self):
		self["filelist"].up()
		self.updateTarget()
		
	#===========================================================================
	# 
	#===========================================================================
	def down(self):
		self["filelist"].down()
		self.updateTarget()
		
	#===========================================================================
	# 
	#===========================================================================
	def left(self):
		self["filelist"].pageUp()
		self.updateTarget()
		
	#===========================================================================
	# 
	#===========================================================================
	def right(self):
		self["filelist"].pageDown()
		self.updateTarget()

	#===========================================================================
	# 
	#===========================================================================
	def ok(self):
		if self["filelist"].canDescent():
			self["filelist"].descent()
			self.updateTarget()
	
	#===========================================================================
	# 
	#===========================================================================
	def updateTarget(self):
		currFolder = str(self["filelist"].getCurrentDirectory())
		currFile = str(self.filelist.getCurrentDirectory()) + str(self.filelist.getFilename())
		if currFolder is not None:
			self["help"].setText(_("Selected file: %s") %(currFile))
		else:
			self["help"].setText(_("Invalid Location"))
Example #15
0
class picshow(Screen):
    skin = """
		<screen name="picshow" position="center,80" size="1200,610" title="PicturePlayer">
			<ePixmap pixmap="skin_default/buttons/red.png" position="10,5" size="200,40"  />
			<ePixmap pixmap="skin_default/buttons/green.png" position="210,5" size="200,40"  />
			<ePixmap pixmap="skin_default/buttons/yellow.png" position="410,5" size="200,40"  />
			<ePixmap pixmap="skin_default/buttons/blue.png" position="610,5" size="200,40"  />
			<widget source="key_red" render="Label" position="10,5" 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="key_green" render="Label" position="210,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-2,-2" />
			<widget source="key_yellow" render="Label" position="410,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="610,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-2,-2" />
			<widget source="global.CurrentTime" render="Label" position="1130,12" size="60,25" font="Regular;22" halign="right">
				<convert type="ClockToText">Default</convert>
			</widget>
			<widget source="global.CurrentTime" render="Label" position="820,12" size="300,25" font="Regular;22" halign="right">
				<convert type="ClockToText">Format:%A %d. %B</convert>
			</widget>
			<eLabel position="10,50" size="1180,1" backgroundColor="grey" />
			<eLabel position="380,50" size="1,585" backgroundColor="grey" />
			<widget name="path" position="400,60" size="790,30" font="Regular;24"/>
			<eLabel position="380,90" size="810,1" backgroundColor="grey" />
			<widget source="label" render="Label" position="20,370" size="330,140" font="Regular;19"/>
			<widget name="thn" position="40,60" size="300,300" />
			<widget name="filelist" position="400,95" size="790,510" scrollbarMode="showOnDemand" />
		</screen>"""

    def __init__(self, session):
        Screen.__init__(self, session)

        self["actions"] = ActionMap(
            ["OkCancelActions", "ColorActions", "DirectionActions"], {
                "cancel": self.KeyExit,
                "red": self.KeyExit,
                "green": self.KeyGreen,
                "yellow": self.KeyYellow,
                "blue": self.KeyBlue,
                "ok": self.KeyOk
            }, -1)

        self["key_red"] = StaticText(_("Close"))
        self["key_green"] = StaticText(_("Thumbnails"))
        self["key_yellow"] = StaticText("")
        self["key_blue"] = StaticText(_("Setup"))
        self["label"] = StaticText("")
        self["thn"] = Pixmap()

        currDir = config.pic.lastDir.value
        if not pathExists(currDir):
            currDir = "/"

        self["path"] = Label(currDir)

        self.filelist = FileList(
            currDir, matchingPattern="(?i)^.*\.(jpeg|jpg|jpe|png|bmp|gif)")
        self["filelist"] = self.filelist
        self["filelist"].onSelectionChanged.append(self.selectionChanged)

        self.ThumbTimer = eTimer()
        self.ThumbTimer_conn = self.ThumbTimer.timeout.connect(self.showThumb)

        self.picload = ePicLoad()
        self.picload_conn = self.picload.PictureData.connect(self.showPic)

        self.onLayoutFinish.append(self.setConf)

    def showPic(self, picInfo=""):
        ptr = self.picload.getData()
        if ptr != None:
            setPixmap(self["thn"], ptr, self._scaleSize, self._aspectRatio)
            self["thn"].show()

        text = picInfo.split('\n', 1)
        self["label"].setText(text[1])
        self["key_yellow"].setText(_("Exif"))

    def showThumb(self):
        if not self.filelist.canDescent():
            if self.filelist.getCurrentDirectory(
            ) and self.filelist.getFilename():
                if self.picload.getThumbnail(
                        self.filelist.getCurrentDirectory() +
                        self.filelist.getFilename()) == 1:
                    self.ThumbTimer.start(config.pic.thumbDelay.value, True)

    def selectionChanged(self):
        if not self.filelist.canDescent():
            self.ThumbTimer.start(config.pic.thumbDelay.value, True)
        else:
            self["label"].setText("")
            self["thn"].hide()
            self["key_yellow"].setText("")

    def KeyGreen(self):
        #if not self.filelist.canDescent():
        self.session.openWithCallback(self.callbackView, Pic_Thumb,
                                      self.filelist.getFileList(),
                                      self.filelist.getSelectionIndex(),
                                      self.filelist.getCurrentDirectory())

    def KeyYellow(self):
        if not self.filelist.canDescent():
            self.session.open(
                Pic_Exif,
                self.picload.getInfo(self.filelist.getCurrentDirectory() +
                                     self.filelist.getFilename()))

    def KeyBlue(self):
        self.session.openWithCallback(self.setConf, Pic_Setup)

    def KeyOk(self):
        if self.filelist.canDescent():
            self.filelist.descent()
            self["path"].setText(self.filelist.getCurrentDirectory())
        else:
            self.session.openWithCallback(self.callbackView, Pic_Full_View,
                                          self.filelist.getFileList(),
                                          self.filelist.getSelectionIndex(),
                                          self.filelist.getCurrentDirectory())

    def setConf(self):
        self.setTitle(_("PicturePlayer"))
        sc = getScale()
        self._aspectRatio = eSize(sc[0], sc[1])
        self._scaleSize = self["thn"].instance.size()
        #0=Width 1=Height 2=Aspect 3=use_cache 4=resize_type 5=Background(#AARRGGBB)
        params = (self._scaleSize.width(), self._scaleSize.height(),
                  sc[0], sc[1], config.pic.cache.value,
                  int(config.pic.resize.value), "#00000000")
        self.picload.setPara(params)

    def callbackView(self, val=0):
        if val > 0:
            self.filelist.moveToIndex(val)

    def KeyExit(self):
        self.ThumbTimer.stop()
        del self.picload_conn
        del self.picload

        if self.filelist.getCurrentDirectory() is None:
            config.pic.lastDir.value = "/"
        else:
            config.pic.lastDir.value = self.filelist.getCurrentDirectory()

        config.pic.save()
        self.close()
Example #16
0
class FlashImageConfig(Screen):
    def __init__(self, session, curdir, matchingPattern=None):
        try:
            sz_w = getDesktop(0).size().width()
        except:
            sz_w = 720

        if sz_w == 1920:
            self.skin = skinflashfullhd
        elif sz_w >= 1280:
            self.skin = skinflashhd
        else:
            self.skin = skinflashsd
        Screen.__init__(self, session)
        self['Title'].setText(_('Select the folder with backup'))
        self['key_red'] = StaticText(_('Close'))
        self['key_green'] = StaticText('')
        self['key_yellow'] = StaticText('')
        self['key_blue'] = StaticText('')
        self['curdir'] = StaticText(_('current:  %s') % (curdir or ''))
        self.founds = False
        self.dualboot = self.dualBoot()
        self.ForceMode = self.ForceMode()
        self.filelist = FileList(curdir,
                                 matchingPattern=matchingPattern,
                                 enableWrapAround=True)
        self.filelist.onSelectionChanged.append(self.__selChanged)
        self['filelist'] = self.filelist
        self['FilelistActions'] = ActionMap(
            ['SetupActions', 'ColorActions'], {
                'green': self.keyGreen,
                'red': self.keyRed,
                'yellow': self.keyYellow,
                'blue': self.KeyBlue,
                'ok': self.keyOk,
                'cancel': self.keyRed
            })
        self.onLayoutFinish.append(self.__layoutFinished)

    def __layoutFinished(self):
        pass

    def dualBoot(self):
        if getBoxType() == 'et8500':
            rootfs2 = False
            kernel2 = False
            f = open('/proc/mtd')
            l = f.readlines()
            for x in l:
                if 'rootfs2' in x:
                    rootfs2 = True
                if 'kernel2' in x:
                    kernel2 = True

            f.close()
            if rootfs2 and kernel2:
                return True
        return False

    def ForceMode(self):
        if getBoxType() in ('h9', 'h9combo', 'i55plus', 'h10'):
            return True
        return False

    def getCurrentSelected(self):
        dirname = self.filelist.getCurrentDirectory()
        filename = self.filelist.getFilename()
        if not filename and not dirname:
            cur = ''
        elif not filename:
            cur = dirname
        elif not dirname:
            cur = filename
        elif not self.filelist.canDescent() or len(filename) <= len(dirname):
            cur = dirname
        else:
            cur = filename
        return cur or ''

    def __selChanged(self):
        self['key_yellow'].setText('')
        self['key_green'].setText('')
        self['key_blue'].setText('')
        self['curdir'].setText(_('current:  %s') % self.getCurrentSelected())
        file_name = self.getCurrentSelected()
        try:
            if not self.filelist.canDescent(
            ) and file_name != '' and file_name != '/':
                filename = self.filelist.getFilename()
                if filename and filename.endswith('.zip'):
                    self['key_yellow'].setText(_('Unzip'))
            elif self.filelist.canDescent(
            ) and file_name != '' and file_name != '/':
                self['key_green'].setText(_('Run flash'))
                if os.path.isfile(file_name +
                                  LOGFILE) and os.path.isfile(file_name +
                                                              VERSIONFILE):
                    self['key_yellow'].setText(_('Backup info'))
                    self['key_blue'].setText(_('Delete'))
        except:
            pass

    def keyOk(self):
        if self.filelist.canDescent():
            self.filelist.descent()

    def confirmedWarning(self, result):
        if result:
            self.founds = False
            self.showparameterlist()

    def keyGreen(self):
        if self['key_green'].getText() == _('Run flash'):
            dirname = self.filelist.getCurrentDirectory()
            if dirname:
                warning_text = '\n'
                if self.dualboot:
                    warning_text += _('\nYou are using dual multiboot!')
                self.session.openWithCallback(
                    lambda r: self.confirmedWarning(r), MessageBox,
                    _("Warning!\nUse at your own risk! Make always a backup before use!\nDon't use it if you use multiple ubi volumes in ubi layer!"
                      ) + warning_text, MessageBox.TYPE_INFO)

    def showparameterlist(self):
        if self['key_green'].getText() == _('Run flash'):
            dirname = self.getCurrentSelected()
            model = getBoxType()
            if dirname:
                backup_files = []
                no_backup_files = []
                text = _('Select parameter for start flash!\n')
                text += _('For flashing your receiver files are needed:\n')
                if model.startswith('dm'):
                    if 'dm9' in model:
                        backup_files = ['kernel.bin', 'rootfs.tar.bz2']
                        no_backup_files = [
                            'kernel_cfe_auto.bin', 'rootfs.bin',
                            'root_cfe_auto.jffs2', 'root_cfe_auto.bin',
                            'oe_kernel.bin', 'oe_rootfs.bin',
                            'kernel_auto.bin', 'uImage', 'rootfs.ubi'
                        ]
                        text += 'kernel.bin, rootfs.tar.bz2'
                    elif model in ('dm520', 'dm7080', 'dm820'):
                        backup_files = ['*.xz']
                        no_backup_files = [
                            'kernel_cfe_auto.bin', 'rootfs.bin',
                            'root_cfe_auto.jffs2', 'root_cfe_auto.bin',
                            'oe_kernel.bin', 'oe_rootfs.bin',
                            'kernel_auto.bin', 'kernel.bin', 'rootfs.tar.bz2',
                            'uImage', 'rootfs.ubi'
                        ]
                        text += '*.xz'
                    else:
                        backup_files = ['*.nfi']
                        no_backup_files = [
                            'kernel_cfe_auto.bin', 'rootfs.bin',
                            'root_cfe_auto.jffs2', 'root_cfe_auto.bin',
                            'oe_kernel.bin', 'oe_rootfs.bin',
                            'kernel_auto.bin', 'kernel.bin', 'rootfs.tar.bz2',
                            'uImage', 'rootfs.ubi'
                        ]
                        text += '*.nfi'
                elif model.startswith('gb'):
                    if '4k' not in model:
                        backup_files = ['kernel.bin', 'rootfs.bin']
                        no_backup_files = [
                            'kernel_cfe_auto.bin', 'root_cfe_auto.jffs2',
                            'root_cfe_auto.bin', 'oe_kernel.bin',
                            'oe_rootfs.bin', 'rootfs.tar.bz2',
                            'kernel_auto.bin', 'uImage', 'rootfs.ubi'
                        ]
                        text += 'kernel.bin, rootfs.bin'
                    else:
                        backup_files = ['kernel.bin', 'rootfs.tar.bz2']
                        no_backup_files = [
                            'kernel_cfe_auto.bin', 'rootfs.bin',
                            'root_cfe_auto.jffs2', 'root_cfe_auto.bin',
                            'oe_kernel.bin', 'oe_rootfs.bin',
                            'kernel_auto.bin', 'uImage', 'rootfs.ubi'
                        ]
                        text += 'kernel.bin, rootfs.tar.bz2'
                elif model.startswith('vu'):
                    if '4k' in model:
                        backup_files = ['kernel_auto.bin', 'rootfs.tar.bz2']
                        no_backup_files = [
                            'kernel_cfe_auto.bin', 'rootfs.bin',
                            'root_cfe_auto.jffs2', 'root_cfe_auto.bin',
                            'oe_kernel.bin', 'oe_rootfs.bin', 'kernel.bin',
                            'uImage', 'rootfs.ubi'
                        ]
                        text += 'kernel_auto.bin, rootfs.tar.bz2'
                    elif model in ('vuduo2', 'vusolose', 'vusolo2', 'vuzero'):
                        backup_files = [
                            'kernel_cfe_auto.bin', 'root_cfe_auto.bin'
                        ]
                        no_backup_files = [
                            'rootfs.bin', 'root_cfe_auto.jffs2',
                            'oe_kernel.bin', 'oe_rootfs.bin', 'kernel.bin',
                            'rootfs.tar.bz2', 'kernel_auto.bin', 'uImage',
                            'rootfs.ubi'
                        ]
                        text += 'kernel_cfe_auto.bin, root_cfe_auto.bin'
                    else:
                        backup_files = [
                            'kernel_cfe_auto.bin', 'root_cfe_auto.jffs2'
                        ]
                        no_backup_files = [
                            'rootfs.bin', 'root_cfe_auto.bin', 'oe_kernel.bin',
                            'oe_rootfs.bin', 'kernel.bin', 'rootfs.tar.bz2',
                            'kernel_auto.bin', 'uImage', 'rootfs.ubi'
                        ]
                        text += 'kernel_cfe_auto.bin, root_cfe_auto.jffs2'
                elif model in ('hd51', 'h7', 'sf4008', 'sf5008', 'sf8008',
                               'vs1500', 'et11000', 'et13000', 'bre2ze4k',
                               'spycat4k', 'spycat4kmini', 'protek4k',
                               'e4hdultra', 'cc1', 'spycatminiv2',
                               'iziboxecohd', 'jdhdduo', 'turing',
                               'arivacombo', 'arivatwin') or model.startswith(
                                   ('anadol', 'axashis4', 'dinobot4',
                                    'ferguson4', 'mediabox4', 'axashisc4')):
                    backup_files = ['kernel.bin', 'rootfs.tar.bz2']
                    no_backup_files = [
                        'kernel_cfe_auto.bin', 'rootfs.bin',
                        'root_cfe_auto.jffs2', 'root_cfe_auto.bin',
                        'oe_kernel.bin', 'oe_rootfs.bin', 'kernel_auto.bin',
                        'uImage', 'rootfs.ubi'
                    ]
                    text += 'kernel.bin, rootfs.tar.bz2'
                elif model in ('h9', 'h9combo', 'i55plus', 'h10', 'dinobotu55',
                               'iziboxx3', 'dinoboth265', 'axashistwin',
                               'protek4kx1'):
                    backup_files = ['uImage', 'rootfs.ubi']
                    no_backup_files = [
                        'kernel_cfe_auto.bin', 'root_cfe_auto.jffs2',
                        'root_cfe_auto.bin', 'oe_kernel.bin', 'oe_rootfs.bin',
                        'rootfs.tar.bz2', 'kernel_auto.bin', 'kernel.bin',
                        'rootfs.tar.bz2'
                    ]
                    text += 'uImage, rootfs.ubi'
                elif model in ('hd60', 'hd61', 'multibox', 'multiboxplus',
                               'v8plus'):
                    backup_files = ['uImage', 'rootfs.tar.bz2']
                    no_backup_files = [
                        'kernel_cfe_auto.bin', 'root_cfe_auto.jffs2',
                        'root_cfe_auto.bin', 'oe_kernel.bin', 'oe_rootfs.bin',
                        'rootfs.ubi', 'kernel_auto.bin', 'kernel.bin'
                    ]
                    text += 'uImage, rootfs.tar.bz2'
                elif model.startswith(
                    ('et4', 'et5', 'et6', 'et7', 'et8', 'et9', 'et10')):
                    backup_files = ['kernel.bin', 'rootfs.bin']
                    no_backup_files = [
                        'kernel_cfe_auto.bin', 'root_cfe_auto.jffs2',
                        'root_cfe_auto.bin', 'oe_kernel.bin', 'oe_rootfs.bin',
                        'rootfs.tar.bz2', 'kernel_auto.bin', 'uImage',
                        'rootfs.ubi'
                    ]
                    text += 'kernel.bin, rootfs.bin'
                elif model.startswith('ebox'):
                    backup_files = [
                        'kernel_cfe_auto.bin', 'root_cfe_auto.jffs2'
                    ]
                    no_backup_files = [
                        'rootfs.bin', 'root_cfe_auto.bin', 'oe_kernel.bin',
                        'oe_rootfs.bin', 'kernel.bin', 'rootfs.tar.bz2',
                        'kernel_auto.bin', 'uImage', 'rootfs.ubi'
                    ]
                    text += 'kernel_cfe_auto.bin, root_cfe_auto.jffs2'
                elif model.startswith(
                    ('fusion', 'pure', 'optimus', 'force', 'iqon', 'ios',
                     'tm2', 'tmn', 'tmt', 'tms', 'lunix', 'mediabox', 'vala')):
                    backup_files = ['oe_kernel.bin', 'oe_rootfs.bin']
                    no_backup_files = [
                        'kernel_cfe_auto.bin', 'rootfs.bin',
                        'root_cfe_auto.jffs2', 'root_cfe_auto.bin',
                        'kernel.bin', 'rootfs.tar.bz2', 'kernel_auto.bin',
                        'uImage', 'rootfs.ubi'
                    ]
                    text += 'oe_kernel.bin, oe_rootfs.bin'
                elif '4k' or 'uhd' in model:
                    backup_files = ['oe_kernel.bin', 'rootfs.tar.bz2']
                    no_backup_files = [
                        'kernel_cfe_auto.bin', 'rootfs.bin',
                        'root_cfe_auto.jffs2', 'root_cfe_auto.bin',
                        'oe_rootfs.bin', 'kernel.bin', 'kernel_auto.bin',
                        'uImage', 'rootfs.ubi'
                    ]
                    text += 'oe_kernel.bin, rootfs.tar.bz2'
                else:
                    backup_files = ['kernel.bin', 'rootfs.bin']
                    no_backup_files = [
                        'kernel_cfe_auto.bin', 'root_cfe_auto.jffs2',
                        'root_cfe_auto.bin', 'oe_kernel.bin', 'oe_rootfs.bin',
                        'rootfs.tar.bz2', 'kernel_auto.bin', 'uImage',
                        'rootfs.ubi'
                    ]
                    text += 'kernel.bin, rootfs.bin'
                try:
                    self.founds = False
                    text += _('\nThe found files:')
                    for name in os.listdir(dirname):
                        if name in backup_files:
                            text += _('  %s (maybe ok)') % name
                            self.founds = True
                        if name in no_backup_files:
                            text += _('  %s (maybe error)') % name
                            self.founds = True

                    if not self.founds:
                        text += _(' nothing!')
                except:
                    pass

                if self.founds:
                    open_list = [(_('Simulate (no write)'), 'simulate'),
                                 (_('Standard (root and kernel)'), 'standard'),
                                 (_('Only root'), 'root'),
                                 (_('Only kernel'), 'kernel')]
                    open_list2 = [
                        (_('Simulate second partition (no write)'),
                         'simulate2'),
                        (_('Second partition (root and kernel)'), 'standard2'),
                        (_('Second partition (only root)'), 'rootfs2'),
                        (_('Second partition (only kernel)'), 'kernel2')
                    ]
                    if self.dualboot:
                        open_list += open_list2
                else:
                    open_list = [(_('Exit'), 'exit')]
                self.session.openWithCallback(self.Callbackflashing,
                                              MessageBox,
                                              text,
                                              simple=True,
                                              list=open_list)

    def Callbackflashing(self, ret):
        if ret:
            if ret == 'exit':
                self.close()
                return
            if self.session.nav.RecordTimer.isRecording():
                self.session.open(
                    MessageBox,
                    _('A recording is currently running. Please stop the recording before trying to start a flashing.'
                      ), MessageBox.TYPE_ERROR)
                self.founds = False
                return
            dir_flash = self.getCurrentSelected()
            text = _('Flashing: ')
            cmd = 'echo -e'
            if ret == 'simulate':
                text += _('Simulate (no write)')
                cmd = "%s -n '%s'" % (ofgwrite_bin, dir_flash)
            elif ret == 'standard':
                text += _('Standard (root and kernel)')
                if self.ForceMode:
                    cmd = "%s -f -r -k '%s' > /dev/null 2>&1 &" % (
                        ofgwrite_bin, dir_flash)
                else:
                    cmd = "%s -r -k '%s' > /dev/null 2>&1 &" % (ofgwrite_bin,
                                                                dir_flash)
            elif ret == 'root':
                text += _('Only root')
                cmd = "%s -r '%s' > /dev/null 2>&1 &" % (ofgwrite_bin,
                                                         dir_flash)
            elif ret == 'kernel':
                text += _('Only kernel')
                cmd = "%s -k '%s' > /dev/null 2>&1 &" % (ofgwrite_bin,
                                                         dir_flash)
            elif ret == 'simulate2':
                text += _('Simulate second partition (no write)')
                cmd = "%s -kmtd3 -rmtd4 -n '%s'" % (ofgwrite_bin, dir_flash)
            elif ret == 'standard2':
                text += _('Second partition (root and kernel)')
                cmd = "%s -kmtd3 -rmtd4 '%s' > /dev/null 2>&1 &" % (
                    ofgwrite_bin, dir_flash)
            elif ret == 'rootfs2':
                text += _('Second partition (only root)')
                cmd = "%s -rmtd4 '%s' > /dev/null 2>&1 &" % (ofgwrite_bin,
                                                             dir_flash)
            elif ret == 'kernel2':
                text += _('Second partition (only kernel)')
                cmd = "%s -kmtd3 '%s' > /dev/null 2>&1 &" % (ofgwrite_bin,
                                                             dir_flash)
            else:
                return
            message = "echo -e '\n"
            message += _('NOT found files for flashing!\n')
            message += "'"
            if ret == 'simulate' or ret == 'simulate2':
                if self.founds:
                    message = "echo -e '\n"
                    message += _('Show only found image and mtd partitions.\n')
                    message += "'"
            elif self.founds:
                message = "echo -e '\n"
                message += _(
                    'ofgwrite will stop enigma2 now to run the flash.\n')
                message += _(
                    'Your STB will freeze during the flashing process.\n')
                message += _(
                    'Please: DO NOT reboot your STB and turn off the power.\n')
                message += _(
                    'The image or kernel will be flashing and auto booted in few minutes.\n'
                )
                message += "'"
            self.session.open(Console, text, [message, cmd])

    def keyRed(self):
        self.close()

    def keyYellow(self):
        if self['key_yellow'].getText() == _('Unzip'):
            filename = self.filelist.getFilename()
            if filename and filename.endswith('.zip'):
                self.session.openWithCallback(
                    self.doUnzip, MessageBox,
                    _('Do you really want to unpack %s ?') % filename,
                    MessageBox.TYPE_YESNO)
        elif self['key_yellow'].getText() == _('Backup info'):
            self.session.open(MessageBox, '\n\n\n%s' % self.getBackupInfo(),
                              MessageBox.TYPE_INFO)

    def getBackupInfo(self):
        backup_dir = self.getCurrentSelected()
        backup_info = ''
        for line in open(backup_dir + VERSIONFILE, 'r'):
            backup_info += line

        return backup_info

    def doUnzip(self, answer):
        if answer is True:
            dirname = self.filelist.getCurrentDirectory()
            filename = self.filelist.getFilename()
            if dirname and filename:
                try:
                    os.system('unzip -o %s%s -d %s' %
                              (dirname, filename, dirname))
                    self.filelist.refresh()
                except:
                    pass

    def confirmedDelete(self, answer):
        if answer is True:
            backup_dir = self.getCurrentSelected()
            cmdmessage = "echo -e 'Removing backup:   %s\n'" % os.path.basename(
                backup_dir.rstrip('/'))
            cmddelete = 'rm -rf %s > /dev/null 2>&1' % backup_dir
            self.session.open(Console, _('Delete backup'),
                              [cmdmessage, cmddelete], self.filelist.refresh)

    def KeyBlue(self):
        if self['key_blue'].getText() == _('Delete'):
            self.session.openWithCallback(
                self.confirmedDelete, MessageBox,
                _('You are about to delete this backup:\n\n%s\nContinue?') %
                self.getBackupInfo(), MessageBox.TYPE_YESNO)
class Selectmusic(Screen):

    def __init__(self, session):
        Screen.__init__(self, session)
        self['actions'] = HelpableActionMap(self, 'MC_AudioPlayerActions', {'ok': (self.KeyOk, 'Play selected file'),
         'left': (self.leftUp, 'List Top'),
         'right': (self.rightDown, 'List Bottom'),
         'up': (self.up, 'List up'),
         'down': (self.down, 'List down')}, -2)
        self['OkCancelActions'] = HelpableActionMap(self, 'OkCancelActions', {'cancel': self.close}, -2)
        currDir = config.plugins.mc_ap.lastDir.value
        if not pathExists(currDir):
            currDir = '/'
        inhibitDirs = ['/bin',
         '/boot',
         '/dev',
         '/dev.static',
         '/etc',
         '/lib',
         '/proc',
         '/ram',
         '/root',
         '/sbin',
         '/sys',
         '/tmp',
         '/usr',
         '/var']
        self.filelist = FileList(currDir, useServiceRef=True, showDirectories=True, showFiles=True, matchingPattern='(?i)^.*\\.(m3u|mp2|mp3|wav|wave|pls|wma|m4a|ogg|ra|flac)', inhibitDirs=inhibitDirs)
        self['filelist'] = self.filelist
        self['currentfolder'] = Label()
        self['currentfolder'].setText(str(currDir))

    def up(self):
        self['filelist'].up()

    def down(self):
        self['filelist'].down()

    def leftUp(self):
        self['filelist'].pageUp()

    def rightDown(self):
        self['filelist'].pageDown()

    def KeyOk(self):
        self.filename = self.filelist.getFilename()
        self['currentfolder'].setText(str(self.filelist.getCurrentDirectory()))
        if self.filelist.getFilename() is not None:
            if self.filelist.canDescent():
                self.filelist.descent()
            else:
                config.plugins.mc_pp.music.value = self.filename
                config.plugins.mc_pp.save()
                self.close()
        elif self.filelist.canDescent():
            self.filelist.descent()
        else:
            config.plugins.mc_pp.music.value = self.filename
            config.plugins.mc_pp.save()
            self.close()
        return
class MC_PictureViewer(Screen, HelpableScreen):

    def __init__(self, session):
        Screen.__init__(self, session)
        HelpableScreen.__init__(self)
        self['key_green'] = Button('Slide Show')
        self['key_yellow'] = Button('Thumb View')
        self['currentfolder'] = Label('')
        self['currentfavname'] = Label('')
        self['actions'] = HelpableActionMap(self, 'MC_PictureViewerActions', {'ok': (self.KeyOk, 'Show Picture'),
         'cancel': (self.Exit, 'Exit Picture Viewer'),
         'left': (self.leftUp, 'List Top'),
         'right': (self.rightDown, 'List Bottom'),
         'up': (self.up, 'List up'),
         'down': (self.down, 'List down'),
         'info': (self.StartExif, 'Show File Info'),
         'green': (self.startslideshow, 'Start Slideshow'),
         'yellow': (self.StartThumb, 'Thumb View'),
         'blue': (self.Settings, 'Settings')}, -2)
        self.aspect = getAspect()
        currDir = config.plugins.mc_pp.lastDir.value
        if not pathExists(currDir):
            currDir = '/'
        self['currentfolder'].setText(str(currDir))
        self.filelist = []
        self['filelist'] = []
        inhibitDirs = ['/bin',
         '/boot',
         '/dev',
         '/dev.static',
         '/etc',
         '/lib',
         '/proc',
         '/ram',
         '/root',
         '/sbin',
         '/sys',
         '/tmp',
         '/usr',
         '/var']
        self.filelist = FileList(currDir, showDirectories=True, showFiles=True, showMountpoints=True, isTop=False, matchingPattern='(?i)^.*\\.(jpeg|jpg|jpe|png|bmp)', inhibitDirs=inhibitDirs)
        self['filelist'] = self.filelist
        self['filelist'].show()
        self['thumbnail'] = Pixmap()
        self.ThumbTimer = eTimer()
        self.ThumbTimer.callback.append(self.showThumb)
        self.ThumbTimer.start(500, True)
        self.picload = ePicLoad()

    def startslideshow(self):
        self.session.openWithCallback(self.returnVal, MC_PicView, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory(), True)

    def up(self):
        self['filelist'].up()
        self.ThumbTimer.start(500, True)

    def down(self):
        self['filelist'].down()
        self.ThumbTimer.start(500, True)

    def leftUp(self):
        self['filelist'].pageUp()
        self.ThumbTimer.start(500, True)

    def rightDown(self):
        self['filelist'].pageDown()
        self.ThumbTimer.start(500, True)

    def showPic(self, picInfo = ''):
        ptr = self.picload.getData()
        if ptr != None:
            self['thumbnail'].instance.setPixmap(ptr.__deref__())
            self['thumbnail'].show()
        return

    def showThumb(self):
        return
        if not self.filelist.canDescent():
            if self.picload.getThumbnail(self.filelist.getCurrentDirectory() + self.filelist.getFilename()) == 1:
                ptr = self.picload.getData()
            else:
                ptr = None
            if ptr != None:
                self['thumbnail'].instance.setPixmap(ptr.__deref__())
                self['thumbnail'].show()
        else:
            self['thumbnail'].hide()
        return

    def KeyOk(self):
        if self.filelist.canDescent():
            self.filelist.descent()
        else:
            self.session.openWithCallback(self.returnVal, MC_PicView, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory(), False)

    def StartThumb(self):
        self.session.openWithCallback(self.returnVal, MC_PicThumbViewer, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory())

    def JumpToFolder(self, jumpto = None):
        if jumpto is None:
            return
        else:
            self['filelist'].changeDir(jumpto)
            self['currentfolder'].setText('%s' % jumpto)
            return
            return

    def returnVal(self, val = 0):
        if val > 0:
            for x in self.filelist.getFileList():
                if x[0][1] == True:
                    val += 1

            self.filelist.moveToIndex(val)

    def StartExif(self):
        if not self.filelist.canDescent():
            self.session.open(MessageBox, 'Oh no, bugged in this version :(', MessageBox.TYPE_ERROR)

    def Settings(self):
        self.session.open(MC_PicSetup)

    def Exit(self):
        if self.filelist.getCurrentDirectory() is None:
            config.plugins.mc_pp.lastDir.value = '/'
        else:
            config.plugins.mc_pp.lastDir.value = self.filelist.getCurrentDirectory()
        config.plugins.mc_pp.save()
        self.close()
        return
Example #19
0
class FileBrowser(Screen):
    title = _("File Browser")
    select = _("Select")

    skin = """
		<screen name="FileBrowser_Generic" position="center,120" size="820,520"  title="%s" >
			<widget name="green" position="10,5" size="200,40" pixmap="skin_default/buttons/green.png" alphatest="on"/>
			<widget name="key_green" position="10,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" shadowColor="black" shadowOffset="-2,-2"/>
			<eLabel position="10,50" size="800,1" backgroundColor="grey" />
			<widget name="filelist" position="10,60" size="800,420" scrollbarMode="showOnDemand"/>
			<widget name="status" position="10,490" size="800,20" font="Regular;18" halign="left" foregroundColors="white,white,white" backgroundColors="background,#00DD00,#DD0000"/>
		</screen>""" % (title)

    def __init__(self,
                 session,
                 showDirectories=True,
                 showFiles=True,
                 showMountpoints=True,
                 matchingPattern=None,
                 useServiceRef=False,
                 inhibitDirs=False,
                 inhibitMounts=False,
                 isTop=False,
                 enableWrapAround=False,
                 additionalExtensions=None,
                 closeOnSelection=False):
        Screen.__init__(self, session)
        self.skinName = "FileBrowser_Generic"

        defaultDir = None  # TODO Fix / Config value
        self._closeOnSelection = closeOnSelection
        self._filelist = FileList(defaultDir,
                                  showDirectories=showDirectories,
                                  showFiles=showFiles,
                                  showMountpoints=showMountpoints,
                                  matchingPattern=matchingPattern,
                                  useServiceRef=useServiceRef,
                                  inhibitDirs=inhibitDirs,
                                  inhibitMounts=inhibitMounts,
                                  isTop=isTop,
                                  enableWrapAround=enableWrapAround,
                                  additionalExtensions=additionalExtensions)

        self["filelist"] = self._filelist
        self["status"] = MultiColorLabel("")

        self["key_green"] = Button(_("Add"))
        self["green"] = Pixmap()

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

    def _onShown(self):
        self.summaries.setText(self.title, 1)
        self._onSelectionChanged()
        self._filelist.onSelectionChanged.append(self._onSelectionChanged)

    def _onSelectionChanged(self):
        # Update LCD Stuff
        curDir = self._filelist.getCurrentDirectory()
        if curDir != None:
            self.summaries.setText(curDir, 2)
        else:
            self.summaries.setText("", 2)

        text = None
        if self._filelist.canDescent():
            text = self._filelist.getFilename()
            if text != None:
                text = "./%s" % (text.split('/')[-2])
                self.summaries.setText(text, 3)
            else:
                self.summaries.setText("", 3)

    def createSummary(self):
        return Simple4LineLCDScreen

    def ok(self):
        if self._filelist.canDescent():
            self._filelist.descent()
        else:
            self.selectCurrent()

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

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

    def pageUp(self):
        self._filelist.pageUp()

    def pageDown(self):
        self._filelist.pageDown()

    def selectCurrent(self):
        if self._filelist.canDescent():
            dir = os_path.dirname(self._filelist.getFilename()) + "/"
            if self.selectDirectory(dir):
                self.setStatus(dir)
            else:
                self.setStatus(dir, True)
        else:
            file = self._filelist.getFilename()
            if self.selectFile(self._filelist.getServiceRef()):
                self.setStatus(file)
            else:
                self.setStatus(file, True)

    def setStatus(self, file, error=False):
        if error:
            self["status"].setText(_("ERROR: Cannot add '%s'") % file)
            self["status"].setForegroundColorNum(2)
            self["status"].setBackgroundColorNum(2)
        else:
            self["status"].setText(_("Added '%s'") % file)
            self["status"].setForegroundColorNum(1)
            self["status"].setBackgroundColorNum(1)

    def selectDirectory(self, dir):
        return self.selectFile(dir)

    def selectFile(self, file):
        if file:
            if self._closeOnSelection:
                self.close(file)
                return True

        return False
Example #20
0
class DirectoryBrowser(Screen):
	skin = """<screen name="DirectoryBrowser" position="center,center" size="520,440" title="Directory browser" >
			<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
			<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
			<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
			<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
			<widget source="curdir" render="Label" position="5,50" size="510,20"  font="Regular;20" halign="left" valign="center" backgroundColor="background" transparent="1" noWrap="1" />
			<widget name="filelist" position="5,80" size="510,345" scrollbarMode="showOnDemand" />
		</screen>"""
	
	def __init__(self, session, curdir, matchingPattern=None):
		Screen.__init__(self, session)

		self["key_red"] = StaticText(_("Cancel"))
		self["key_green"] = StaticText(_("Save"))
		self["curdir"] = StaticText("current:  %s"%(curdir or ''))

		self.filelist = FileList(curdir, matchingPattern=matchingPattern, enableWrapAround=True)
		self.filelist.onSelectionChanged.append(self.__selChanged)
		self["filelist"] = self.filelist

		self["FilelistActions"] = ActionMap(["SetupActions", "ColorActions"],
			{
				"green": self.keyGreen,
				"red": self.keyRed,
				"ok": self.keyOk,
				"cancel": self.keyRed
			})
		self.onLayoutFinish.append(self.__layoutFinished)

	def __layoutFinished(self):
		#self.setTitle(_("Directory browser"))
		pass

	def getCurrentSelected(self):
		dirname = self.filelist.getCurrentDirectory()
		filename = self.filelist.getFilename()
		if not filename and not dirname:
			cur = ''
		elif not filename:
			cur = dirname
		elif not dirname:
			cur = filename
		else:
			if not self.filelist.canDescent() or len(filename) <= len(dirname):
				cur = dirname
			else:
				cur = filename
		return cur or ''

	def __selChanged(self):
		self["curdir"].setText("current:  %s"%(self.getCurrentSelected()))

	def keyOk(self):
		if self.filelist.canDescent():
			self.filelist.descent()

	def keyGreen(self):
		self.close(self.getCurrentSelected())

	def keyRed(self):
		self.close(False)
class EL_Screen_PathSelector(Screen):

    #===========================================================================
    #
    #===========================================================================
    def __init__(self, session, initDir, myType, title):
        Screen.__init__(self, session)

        self.guiElements = getGuiElements()

        self.myType = myType
        self.title = title

        if not os.path.exists(initDir):
            initDir = "/etc/"

        self.filelist = FileList("/dev/",
                                 showDirectories=True,
                                 showFiles=True,
                                 showMountpoints=True,
                                 isTop=False,
                                 matchingPattern="")
        self["filelist"] = self.filelist

        #self["filelist"]  = FileList(initDir, showDirectories = True, showFiles = True, showMountpoints = False, isTop = True, matchingPattern = "^.*\.(conf|config)")
        self["filelist"].changeDir(initDir.rsplit('/', 1)[0] + "/",
                                   select=initDir.rsplit('/', 1)[1])
        self["help"] = Label()
        self["help"].setText(initDir)
        self["actions"] = ActionMap(
            [
                "WizardActions", "DirectionActions", "ColorActions",
                "EPGSelectActions"
            ], {
                "back": self.cancel,
                "left": self.left,
                "right": self.right,
                "up": self.up,
                "down": self.down,
                "ok": self.ok,
                "green": self.green,
                "red": self.cancel
            }, -1)

        self["btn_red"] = Pixmap()
        self["btn_redText"] = Label()

        self["btn_green"] = Pixmap()
        self["btn_greenText"] = Label()

        self.onLayoutFinish.append(self.finishLayout)

    #===========================================================================
    #
    #===========================================================================
    def finishLayout(self):
        self["btn_red"].instance.setPixmapFromFile(self.guiElements["key_red"])
        self["btn_redText"].setText(_("Cancel"))

        self["btn_green"].instance.setPixmapFromFile(
            self.guiElements["key_green"])
        self["btn_greenText"].setText(_("Ok"))

        self.setTitle(_(self.title))

    #===========================================================================
    #
    #===========================================================================
    def cancel(self):
        self.close(None, self.myType)

    #===========================================================================
    #
    #===========================================================================
    def green(self):
        self.close(
            str(self["filelist"].getCurrentDirectory()) +
            str(self["filelist"].getSelection()[0]), self.myType)

    #===========================================================================
    #
    #===========================================================================
    def up(self):
        self["filelist"].up()
        self.updateTarget()

    #===========================================================================
    #
    #===========================================================================
    def down(self):
        self["filelist"].down()
        self.updateTarget()

    #===========================================================================
    #
    #===========================================================================
    def left(self):
        self["filelist"].pageUp()
        self.updateTarget()

    #===========================================================================
    #
    #===========================================================================
    def right(self):
        self["filelist"].pageDown()
        self.updateTarget()

    #===========================================================================
    #
    #===========================================================================
    def ok(self):
        if self["filelist"].canDescent():
            self["filelist"].descent()
            self.updateTarget()

    #===========================================================================
    #
    #===========================================================================
    def updateTarget(self):
        currFolder = str(self["filelist"].getCurrentDirectory())
        currFile = str(self.filelist.getCurrentDirectory()) + str(
            self.filelist.getFilename())
        if currFolder is not None:
            self["help"].setText(_("Selected file: %s") % (currFile))
        else:
            self["help"].setText(_("Invalid Location"))
Example #22
0
class picshow(Screen):
	skin = """
		<screen name="picshow" position="center,80" size="1200,610" title="PicturePlayer">
			<ePixmap pixmap="skin_default/buttons/red.png" position="10,5" size="200,40"  />
			<ePixmap pixmap="skin_default/buttons/green.png" position="210,5" size="200,40"  />
			<ePixmap pixmap="skin_default/buttons/yellow.png" position="410,5" size="200,40"  />
			<ePixmap pixmap="skin_default/buttons/blue.png" position="610,5" size="200,40"  />
			<widget source="key_red" render="Label" position="10,5" 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="key_green" render="Label" position="210,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-2,-2" />
			<widget source="key_yellow" render="Label" position="410,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="610,5" size="200,40" zPosition="1" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" foregroundColor="white" shadowColor="black" shadowOffset="-2,-2" />
			<widget source="global.CurrentTime" render="Label" position="1130,12" size="60,25" font="Regular;22" halign="right">
				<convert type="ClockToText">Default</convert>
			</widget>
			<widget source="global.CurrentTime" render="Label" position="820,12" size="300,25" font="Regular;22" halign="right">
				<convert type="ClockToText">Format:%A %d. %B</convert>
			</widget>
			<eLabel position="10,50" size="1180,1" backgroundColor="grey" />
			<eLabel position="380,50" size="1,585" backgroundColor="grey" />
			<widget name="path" position="400,60" size="790,30" font="Regular;24"/>
			<eLabel position="380,90" size="810,1" backgroundColor="grey" />
			<widget source="label" render="Label" position="20,370" size="330,140" font="Regular;19"/>
			<widget name="thn" position="40,60" size="300,300" />
			<widget name="filelist" position="400,95" size="790,510" scrollbarMode="showOnDemand" />
		</screen>"""

	def __init__(self, session):
		Screen.__init__(self, session)

		self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions"],
		{
			"cancel": self.KeyExit,
			"red": self.KeyExit,
			"green": self.KeyGreen,
			"yellow": self.KeyYellow,
			"blue": self.KeyBlue,
			"ok": self.KeyOk
		}, -1)

		self["key_red"] = StaticText(_("Close"))
		self["key_green"] = StaticText(_("Thumbnails"))
		self["key_yellow"] = StaticText("")
		self["key_blue"] = StaticText(_("Setup"))
		self["label"] = StaticText("")
		self["thn"] = Pixmap()


		currDir = config.pic.lastDir.value
		if not pathExists(currDir):
			currDir = "/"

		self["path"] = Label(currDir)

		self.filelist = FileList(currDir, matchingPattern = "(?i)^.*\.(jpeg|jpg|jpe|png|bmp|gif)")
		self["filelist"] = self.filelist
		self["filelist"].onSelectionChanged.append(self.selectionChanged)

		self.ThumbTimer = eTimer()
		self.ThumbTimer_conn = self.ThumbTimer.timeout.connect(self.showThumb)

		self.picload = ePicLoad()
		self.picload_conn = self.picload.PictureData.connect(self.showPic)

		self.onLayoutFinish.append(self.setConf)

	def showPic(self, picInfo=""):
		ptr = self.picload.getData()
		if ptr != None:
			setPixmap(self["thn"], ptr, self._scaleSize, self._aspectRatio)
			self["thn"].show()

		text = picInfo.split('\n',1)
		self["label"].setText(text[1])
		self["key_yellow"].setText(_("Exif"))

	def showThumb(self):
		if not self.filelist.canDescent():
			if self.filelist.getCurrentDirectory() and self.filelist.getFilename():
				if self.picload.getThumbnail(self.filelist.getCurrentDirectory() + self.filelist.getFilename()) == 1:
					self.ThumbTimer.start(config.pic.thumbDelay.value, True)

	def selectionChanged(self):
		if not self.filelist.canDescent():
			self.ThumbTimer.start(config.pic.thumbDelay.value, True)
		else:
			self["label"].setText("")
			self["thn"].hide()
			self["key_yellow"].setText("")

	def KeyGreen(self):
		#if not self.filelist.canDescent():
		self.session.openWithCallback(self.callbackView, Pic_Thumb, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory())

	def KeyYellow(self):
		if not self.filelist.canDescent():
			self.session.open(Pic_Exif, self.picload.getInfo(self.filelist.getCurrentDirectory() + self.filelist.getFilename()))

	def KeyBlue(self):
		self.session.openWithCallback(self.setConf ,Pic_Setup)

	def KeyOk(self):
		if self.filelist.canDescent():
			self.filelist.descent()
			self["path"].setText(self.filelist.getCurrentDirectory())
		else:
			self.session.openWithCallback(self.callbackView, Pic_Full_View, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory())

	def setConf(self):
		self.setTitle(_("PicturePlayer"))
		sc = getScale()
		self._aspectRatio = eSize(sc[0], sc[1])
		self._scaleSize = self["thn"].instance.size()
		#0=Width 1=Height 2=Aspect 3=use_cache 4=resize_type 5=Background(#AARRGGBB)
		params = (self._scaleSize.width(), self._scaleSize.height(), sc[0], sc[1], config.pic.cache.value, int(config.pic.resize.value), "#00000000")
		self.picload.setPara(params)

	def callbackView(self, val=0):
		if val > 0:
			self.filelist.moveToIndex(val)

	def KeyExit(self):
		self.ThumbTimer.stop()
		del self.picload_conn
		del self.picload

		if self.filelist.getCurrentDirectory() is None:
			config.pic.lastDir.value = "/"
		else:
			config.pic.lastDir.value = self.filelist.getCurrentDirectory()

		config.pic.save()
		self.close()
Example #23
0
class subconv(Screen):
    skin = '\n\t\t<screen name="RTiSubtitleConverter007" position="center,center" size="560,290" title="RTi SubtitleConverter   v.1.0" >\n\t\t\t<ePixmap name="red"    position="0,250"   zPosition="2" size="140,40" pixmap="skin_default/buttons/red.png" transparent="1" alphatest="on" />\n\t\t\t<ePixmap name="blue"   position="420,250" zPosition="2" size="140,40" pixmap="skin_default/buttons/blue.png" transparent="1" alphatest="on" /> \n\t\t\t<widget name="key_red" position="0,250" size="140,40" valign="center" halign="center" zPosition="4"  foregroundColor="white" font="Regular;20" transparent="1" shadowColor="#25062748" shadowOffset="-2,-2" /> \n\t\t\t<widget name="key_blue" position="420,250" size="140,40" valign="center" halign="center" zPosition="4"  foregroundColor="white" font="Regular;20" transparent="1" shadowColor="background" shadowOffset="-2,-2" />\n\t\t\t<widget name="thn" position="420,250" size="180,160" alphatest="on" />\n\t\t\t<widget name="filelist" position="5,55" zPosition="2" size="550,187" scrollbarMode="showOnDemand" />\n\t\t\t<widget name="info0" position="5,20" zPosition="2" size="550,20" font="Regular;18" foregroundColor="#aaaaaa" transparent="1" halign="center" valign="center" />\n\t\t\t<widget name="infoL" position="140,265" zPosition="2" size="280,20" font="Regular;22" foregroundColor="#ffffff" transparent="1" halign="center" valign="center" />\n\t\t</screen>'
    
    def __init__(self, session):
        Screen.__init__(self, session)
        self['actions'] = ActionMap([
            'OkCancelActions',
            'ColorActions',
            'DirectionActions'], {
            'cancel': self.KeyExit,
            'red': self.KeyOk,
            'blue': self.KeyExit,
            'ok': self.KeyOk }, -1)
        self['key_blue'] = Button(_('Exit'))
        self['key_red'] = Button(_('Select'))
        self['thn'] = Pixmap()
        self['info0'] = Label()
        self['infoL'] = Label()
        currDir = config.pic.lastDir.value
        if not pathExists(currDir):
            currDir = '/'
        
        self.filelist = FileList(currDir, matchingPattern = '(?i)^.*\\.(srt|sub|txt)')
        self['filelist'] = self.filelist
        self['info0'].setText('Select Subtitle for conversion :')
        self['infoL'].setText('www.azbox-enigma.eu')

    
    def KeyGreen(self):
        print 'ok'

    
    def KeyYellow(self):
        if not self.filelist.canDescent():
            print 'ok'
        

    
    def KeyBlue(self):
        print 'ok'

    
    def KeyOk(self):
        if self.filelist.canDescent():
            self.filelist.descent()
        else:
            pateka = '/'
            ime = self.filelist.getFileList()
            if self.filelist.getCurrentDirectory() and self.filelist.getFilename():
                ime = self.filelist.getFileList()
                ind = self.filelist.getSelectionIndex()
                pateka = self.filelist.getCurrentDirectory() + ime[ind][0][0]
            
            self.session.open(SubPreview, str(pateka))

    
    def callbackView(self, val = 0):
        if val > 0:
            self.filelist.moveToIndex(val)
        

    
    def KeyExit(self):
        print 'exit'
        if self.filelist.getCurrentDirectory() is None:
            config.pic.lastDir.value = '/'
        else:
            config.pic.lastDir.value = self.filelist.getCurrentDirectory()
        config.pic.save()
        self.close()
Example #24
0
File: ui.py Project: ambrosa/test
class picshow(Screen):
	skin = """
		<screen name="picshow" position="center,center" size="560,440" title="PicturePlayer" >
			<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
			<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
			<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
			<ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
			<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
			<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
			<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
			<widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
			<widget source="label" render="Label" position="5,55" size="350,140" font="Regular;19" backgroundColor="#25062748" transparent="1"  />
			<widget name="thn" position="360,40" size="180,160" alphatest="on" />
			<widget name="filelist" position="5,205" zPosition="2" size="550,230" scrollbarMode="showOnDemand" />
		</screen>"""

	def __init__(self, session):
		Screen.__init__(self, session)

		self["actions"] = ActionMap(["OkCancelActions", "ColorActions", "DirectionActions"],
		{
			"cancel": self.KeyExit,
			"red": self.KeyExit,
			"green": self.KeyGreen,
			"yellow": self.KeyYellow,
			"blue": self.KeyBlue,
			"ok": self.KeyOk
		}, -1)

		self["key_red"] = StaticText(_("Close"))
		self["key_green"] = StaticText(_("Thumbnails"))
		self["key_yellow"] = StaticText("")
		self["key_blue"] = StaticText(_("Setup"))
		self["label"] = StaticText("")
		self["thn"] = Pixmap()

		currDir = config.pic.lastDir.value
		if not pathExists(currDir):
			currDir = "/"

		self.filelist = FileList(currDir, matchingPattern = "(?i)^.*\.(jpeg|jpg|jpe|png|bmp|gif)")
		self["filelist"] = self.filelist
		self["filelist"].onSelectionChanged.append(self.selectionChanged)

		self.ThumbTimer = eTimer()
		self.ThumbTimer.callback.append(self.showThumb)

		self.picload = ePicLoad()
		self.picload.PictureData.get().append(self.showPic)

		self.onLayoutFinish.append(self.setConf)

	def showPic(self, picInfo=""):
		ptr = self.picload.getData()
		if ptr != None:
			self["thn"].instance.setPixmap(ptr.__deref__())
			self["thn"].show()

		text = picInfo.split('\n',1)
		self["label"].setText(text[1])
		self["key_yellow"].setText(_("Exif"))

	def showThumb(self):
		if not self.filelist.canDescent():
			if self.filelist.getCurrentDirectory() and self.filelist.getFilename():
				if self.picload.getThumbnail(self.filelist.getCurrentDirectory() + self.filelist.getFilename()) == 1:
					self.ThumbTimer.start(500, True)

	def selectionChanged(self):
		if not self.filelist.canDescent():
			self.ThumbTimer.start(500, True)
		else:
			self["label"].setText("")
			self["thn"].hide()
			self["key_yellow"].setText("")

	def KeyGreen(self):
		#if not self.filelist.canDescent():
		self.session.openWithCallback(self.callbackView, Pic_Thumb, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory())

	def KeyYellow(self):
		if not self.filelist.canDescent():
			self.session.open(Pic_Exif, self.picload.getInfo(self.filelist.getCurrentDirectory() + self.filelist.getFilename()))

	def KeyBlue(self):
		self.session.openWithCallback(self.setConf ,Pic_Setup)

	def KeyOk(self):
		if self.filelist.canDescent():
			self.filelist.descent()
		else:
			self.session.openWithCallback(self.callbackView, Pic_Full_View, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory())

	def setConf(self):
		self.setTitle(_("PicturePlayer"))
		sc = getScale()
		#0=Width 1=Height 2=Aspect 3=use_cache 4=resize_type 5=Background(#AARRGGBB)
		self.picload.setPara((self["thn"].instance.size().width(), self["thn"].instance.size().height(), sc[0], sc[1], config.pic.cache.value, int(config.pic.resize.value), "#00000000"))

	def callbackView(self, val=0):
		if val > 0:
			self.filelist.moveToIndex(val)

	def KeyExit(self):
		del self.picload

		if self.filelist.getCurrentDirectory() is None:
			config.pic.lastDir.value = "/"
		else:
			config.pic.lastDir.value = self.filelist.getCurrentDirectory()

		config.pic.save()
		self.close()
class MC_PictureViewer(Screen, HelpableScreen):
	def __init__(self, session):
		Screen.__init__(self, session)
		HelpableScreen.__init__(self)
		self["key_green"] = Button("Slide Show")
		self["key_yellow"] = Button("Thumb View")
		self["currentfolder"] = Label("")
		self["currentfavname"] = Label("")
		self["actions"] = HelpableActionMap(self, "MC_PictureViewerActions", 
			{
				"ok": (self.KeyOk, "Show Picture"),
				"cancel": (self.Exit, "Exit Picture Viewer"),
				"left": (self.leftUp, "List Top"),
				"right": (self.rightDown, "List Bottom"),
				"up": (self.up, "List up"),
				"down": (self.down, "List down"),
				"info": (self.StartExif, "Show File Info"),
				"green": (self.startslideshow, "Start Slideshow"),
				"yellow": (self.StartThumb, "Thumb View"),
				"blue": (self.Settings, "Settings"),
			}, -2)

		self.aspect = getAspect()
		currDir = config.plugins.mc_pp.lastDir.value
		if not pathExists(currDir):
			currDir = "/"
		self["currentfolder"].setText(str(currDir))
		self.filelist = []
		self["filelist"] = []
		inhibitDirs = ["/bin", "/boot", "/dev", "/dev.static", "/etc", "/lib" , "/proc", "/ram", "/root" , "/sbin", "/sys", "/tmp", "/usr", "/var"]
		self.filelist = FileList(currDir, showDirectories = True, showFiles = True, showMountpoints = True, isTop = False, matchingPattern = "(?i)^.*\.(jpeg|jpg|jpe|png|bmp)", inhibitDirs = inhibitDirs)
		self["filelist"] = self.filelist
		self["filelist"].show()
		self["thumbnail"] = Pixmap()
		self.ThumbTimer = eTimer()
		self.ThumbTimer.callback.append(self.showThumb)
		self.ThumbTimer.start(500, True)

		self.picload = ePicLoad()
		#self.picload.PictureData.get().append(self.showPic)

	def startslideshow(self):
		self.session.openWithCallback(self.returnVal , MC_PicView, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory(), True)

	def up(self):
		self["filelist"].up()
		self.ThumbTimer.start(500, True)
	def down(self):
		self["filelist"].down()
		self.ThumbTimer.start(500, True)
	def leftUp(self):
		self["filelist"].pageUp()
		self.ThumbTimer.start(500, True)
	def rightDown(self):
		self["filelist"].pageDown()
		self.ThumbTimer.start(500, True)
	def showPic(self, picInfo=""):
		ptr = self.picload.getData()
		if ptr != None:
			self["thumbnail"].instance.setPixmap(ptr.__deref__())
			self["thumbnail"].show()

	def showThumb(self):
		return
		if not self.filelist.canDescent():
			if self.picload.getThumbnail(self.filelist.getCurrentDirectory() + self.filelist.getFilename()) == 1:
				ptr = self.picload.getData()
			else:
				ptr = None
			
			#ptr = loadPic(self.filelist.getCurrentDirectory() + self.filelist.getFilename(), 180, 160, self.aspect, int(config.plugins.mc_pp.resize.value), 0, 0, cachefile)
			if ptr != None:
				self["thumbnail"].instance.setPixmap(ptr.__deref__())
				self["thumbnail"].show()
		else:
			self["thumbnail"].hide()

	def KeyOk(self):
		if self.filelist.canDescent():
			self.filelist.descent()
		else:
			self.session.openWithCallback(self.returnVal, MC_PicView, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory(), False)
	def StartThumb(self):
		self.session.openWithCallback(self.returnVal, MC_PicThumbViewer, self.filelist.getFileList(), self.filelist.getSelectionIndex(), self.filelist.getCurrentDirectory())

	def JumpToFolder(self, jumpto = None):
		if jumpto is None:
			return
		else:
			self["filelist"].changeDir(jumpto)
			self["currentfolder"].setText(("%s") % (jumpto))
	def returnVal(self, val=0):
		if val > 0:
			for x in self.filelist.getFileList():
				if x[0][1] == True:
					val += 1
			self.filelist.moveToIndex(val)

	def StartExif(self):
		if not self.filelist.canDescent():
			#self.session.open(Pic_Exif, self.filelist.getCurrentDirectory() + self.filelist.getFilename(), self.filelist.getFilename())
			#self.session.open(Pic_Exif, self.picload.getInfo(self.filelist.getSelectionIndex()))
			self.session.open(MessageBox, "Oh no, bugged in this version :(", MessageBox.TYPE_ERROR)

	def Settings(self):
		self.session.open(MC_PicSetup)
	def Exit(self):
		if self.filelist.getCurrentDirectory() is None:
			config.plugins.mc_pp.lastDir.value = "/"
		else:
			config.plugins.mc_pp.lastDir.value = self.filelist.getCurrentDirectory()
		config.plugins.mc_pp.save()
		self.close()