Ejemplo n.º 1
0
 def update(self, path):
     if self.type == self.USED:
         try:
             total_size = get_size(getTrashFolder(path))
             total_size = _("%s %sB") % UnitScaler()(total_size)
         except:
             # occurs when f_blocks is 0 or a similar error
             total_size = " -?-"
         self.setText(_("Trash:") + " " + total_size)
Ejemplo n.º 2
0
    def getText(self):
        service = self.source.service
        info = self.source.info
        event = self.source.event
        if info and service:
            if self.type == self.MOVIE_SHORT_DESCRIPTION:
                if (service.flags & eServiceReference.flagDirectory
                    ) == eServiceReference.flagDirectory:
                    # Short description for Directory is the full path
                    return service.getPath()
                return (info.getInfoString(service,
                                           iServiceInformation.sDescription) or
                        (event and self.trimText(event.getShortDescription()))
                        or service.getPath())
            elif self.type == self.MOVIE_META_DESCRIPTION:
                return ((event and
                         (self.trimText(event.getExtendedDescription())
                          or self.trimText(event.getShortDescription())))
                        or info.getInfoString(service,
                                              iServiceInformation.sDescription)
                        or service.getPath())
            elif self.type == self.MOVIE_FULL_DESCRIPTION:
                return ((event and self.formatDescription(
                    event.getShortDescription(),
                    event.getExtendedDescription())) or info.getInfoString(
                        service, iServiceInformation.sDescription)
                        or service.getPath())

            elif self.type == self.MOVIE_REC_SERVICE_NAME:
                rec_ref_str = info.getInfoString(
                    service, iServiceInformation.sServiceref)
                return ServiceReference(rec_ref_str).getServiceName()
            elif self.type == self.MOVIE_REC_SERVICE_REF:
                rec_ref_str = info.getInfoString(
                    service, iServiceInformation.sServiceref)
                return str(ServiceReference(rec_ref_str))
            elif self.type == self.MOVIE_REC_FILESIZE:
                if (service.flags & eServiceReference.flagDirectory
                    ) == eServiceReference.flagDirectory:
                    return _("Directory")
                filesize = info.getFileSize(service)
                if filesize:
                    return _("%s %sB") % UnitScaler()(filesize)
        return ""
Ejemplo n.º 3
0
class key_actions(stat_info):
	hashes = {
		"MD5": "md5sum",
		"SHA1": "sha1sum",
		"SHA3": "sha3sum",
		"SHA256": "sha256sum",
		"SHA512": "sha512sum",
	}

	progPackages = {
		"file": "file",
		"ffprobe": "ffmpeg",
		#  "mediainfo": "mediainfo",
	}

	SIZESCALER = UnitScaler(scaleTable=UnitMultipliers.Jedec, maxNumLen=3, decimals=1)

	def __init__(self):
		stat_info.__init__(self)

	@staticmethod
	def have_program(prog):
		path = os.environ.get('PATH')
		if '/' in prog or not path:
			return os.access(prog, os.X_OK)
		for dir in path.split(':'):
			if os.access(os.path.join(dir, prog), os.X_OK):
				return True
		return False

	def change_mod(self, dirsource):
		filename = dirsource.getFilename()
		sourceDir = dirsource.getCurrentDirectory()  # self.SOURCELIST.getCurrentDirectory()

		if filename is None or sourceDir is None:
			self.session.open(MessageBox, _("It is not possible to change the file mode of <List of Storage Devices>"), type=MessageBox.TYPE_ERROR)
			return

		self.longname = sourceDir + filename
		if not dirsource.canDescent():
			askList = [(_("Set archive mode (644)"), "CHMOD644"), (_("Set executable mode (755)"), "CHMOD755"), (_("Cancel"), "NO")]
			self.session.openWithCallback(self.do_change_mod, ChoiceBox, title=(_("Do you want change rights?\\n") + filename), list=askList)
		else:
			self.session.open(MessageBox, _("Not allowed with folders"), type=MessageBox.TYPE_INFO, close_on_any_key=True)

	def do_change_mod(self, answer):
		answer = answer and answer[1]
		# sourceDir = dirsource.getCurrentDirectory() #self.SOURCELIST.getCurrentDirectory()
		if answer == "CHMOD644":
			os.system("chmod 644 " + self.longname)
		elif answer == "CHMOD755":
			os.system("chmod 755 " + self.longname)
		self.doRefresh()

	def Humanizer(self, size):
		if (size < 1024):
			humansize = str(size) + " B"
		elif (size < 1048576):
			humansize = str(size / 1024) + " KB"
		else:
			humansize = str(round(float(size) / 1048576, 2)) + " MB"
		return humansize

	def Info(self, dirsource):
		filename = dirsource.getFilename()
		sourceDir = dirsource.getCurrentDirectory()
		if dirsource.canDescent():
			if dirsource.getSelectionIndex() != 0:
				if (not sourceDir) and (not filename):
					return pname
				else:
					pathname = filename
		else:
			pathname = sourceDir + filename
		try:
			st = os.lstat(os.path.normpath(pathname))
		except:
			return ""
		info = ' '.join(self.SIZESCALER.scale(st.st_size)) + "B    "
		info += self.formatTime(st.st_mtime) + "    "
		info += _("Mode %s (%04o)") % (self.fileModeStr(st.st_mode), stat.S_IMODE(st.st_mode))
		return info

	def statInfo(self, dirsource):
		filename = dirsource.getFilename()
		sourceDir = dirsource.getCurrentDirectory()
		if dirsource.canDescent():
			if dirsource.getSelectionIndex() != 0:
				if (not sourceDir) and (not filename):
					return pname
				else:
					pathname = filename
		else:
			pathname = sourceDir + filename
		try:
			st = os.lstat(os.path.normpath(pathname))
		except:
			return ()

		# Numbers in trailing comments are the template text indexes
		symbolicmode = self.fileModeStr(st.st_mode)
		octalmode = "%04o" % stat.S_IMODE(st.st_mode)
		modes = (
			octalmode,  # 0
			symbolicmode,  # 1
			_("%s (%s)") % (octalmode, symbolicmode)  # 2
		)

		if stat.S_ISCHR(st.st_mode) or stat.S_ISBLK(st.st_mode):
			sizes = ("", "", "")
		else:
			bytesize = "%s" % "{:n}".format(st.st_size)
			scaledsize = ' '.join(self.SIZESCALER.scale(st.st_size))
			sizes = (
				bytesize,  # 10
				_("%sB") % scaledsize,  # 11
				_("%s (%sB") % (bytesize, scaledsize)  # 12
			)

		return [modes + (
			"%d" % st.st_ino,  # 3
			"%d, %d" % ((st.st_dev >> 8) & 0xff, st.st_dev & 0xff),   # 4
			"%d" % st.st_nlink,  # 5
			"%d" % st.st_uid,  # 6
			"%s" % self.username(st.st_uid),  # 7
			"%d" % st.st_gid,  # 8
			"%s" % self.groupname(st.st_gid)  # 9
		) + sizes + (
			self.formatTime(st.st_mtime),  # 13
			self.formatTime(st.st_atime),  # 14
			self.formatTime(st.st_ctime)  # 15
		)]

	@staticmethod
	def fileFilter():
		if config.plugins.filecommander.extension.value == "myfilter":
			return "^.*\.%s" % config.plugins.filecommander.my_extension.value
		else:
			return config.plugins.filecommander.extension.value

	@staticmethod
	def filterSettings():
		return(
			config.plugins.filecommander.extension.value,
			config.plugins.filecommander.my_extension.value
		)

	def run_script(self, dirsource, dirtarget):
		filename = dirsource.getFilename()
		sourceDir = dirsource.getCurrentDirectory()
		self.commando = sourceDir + filename
		self.parameter = ''
		targetdir = dirtarget.getCurrentDirectory()
		if targetdir is not None:
			file = dirtarget.getFilename() or ''
			if file.startswith(targetdir):
				self.parameter = file
			elif not targetdir.startswith(file):
				self.parameter = targetdir + file
			else:
				self.parameter = targetdir
		stxt = _('python')
		if self.commando.endswith('.sh'):
			stxt = _('shell')
		askList = [(_("Cancel"), "NO"), (_("View or edit this %s script") %stxt, "VIEW"), (_("Run script"), "YES"), (_("Run script in background"), "YES_BG")]
		if self.commando.endswith('.pyo'):
			askList.remove((_("View or edit this %s script") %stxt, "VIEW"))
		if self.parameter:
			askList.append((_("Run script with optional parameter"), "PAR"))
			askList.append((_("Run script with optional parameter in background"), "PAR_BG"))
			filename += _('\noptional parameter:\n%s') %self.parameter
		self.session.openWithCallback(self.do_run_script, ChoiceBox, title=_("Do you want to view or run the script?\n") + filename, list=askList)

	def do_run_script(self, answer):
		answer = answer and answer[1]
		if answer in ("YES", "PAR", "YES_BG", "PAR_BG"):
			if not os.access(self.commando, os.R_OK):
				self.session.open(MessageBox, _("Script '%s' must have read permission to be able to run it") % self.commando, type=MessageBox.TYPE_ERROR, close_on_any_key=True)
				return
			nice = config.plugins.filecommander.script_priority_nice.value or ''
			ionice = config.plugins.filecommander.script_priority_ionice.value or ''
			if nice:
				nice = 'nice -n %d ' %nice
			if ionice:
				ionice = 'ionice -c %d ' %ionice
			priority = '%s%s' %(nice,ionice)
			if self.commando.endswith('.sh'):
				if os.access(self.commando, os.X_OK):
					if 'PAR' in answer:
						cmdline = "%s%s '%s'" %(priority, self.commando, self.parameter)
					else:
						cmdline = "%s%s" %(priority, self.commando)
				else:
					if 'PAR' in answer:
						cmdline = "%s/bin/sh %s '%s'" %(priority, self.commando, self.parameter)
					else:
						cmdline = "%s/bin/sh %s" %(priority, self.commando)
			else:
				if 'PAR' in answer:
					cmdline = "%s/usr/bin/python %s '%s'" %(priority, self.commando, self.parameter)
				else:
					cmdline = "%s/usr/bin/python %s" %(priority, self.commando)
		elif answer == "VIEW":
			try:
				yfile = os.stat(self.commando)
			except OSError as oe:
				self.session.open(MessageBox, _("%s: %s") % (self.commando, oe.strerror), type=MessageBox.TYPE_ERROR)
				return
			if (yfile.st_size < 1000000):
				self.session.open(vEditor, self.commando)

		if answer and answer != "VIEW":
			if answer.endswith('_BG'):
				global task_Stout, task_Sterr
				task_Stout = []
				task_Sterr = []
				if 'PAR' in answer:
					name = '%s%s %s' %(priority, self.commando, self.parameter)
				else:
					name = '%s%s' %(priority, self.commando)
				job = Job(_("Run script") + " ('%s')" %name)
				task = Task(job, name)
				task.postconditions.append(task_postconditions())
				task.processStdout = task_processStdout
				task.processStderr = task_processSterr
				task.setCmdline(cmdline)
				job_manager.AddJob(job, onSuccess=self.finishedCB, onFail=self.failCB)
				self.jobs += 1
				self.onLayout()
			else:
				self.session.open(Console, cmdlist=(cmdline,))

	def run_file(self):
		if self.disableActions_Timer.isActive():
			return
		self.run_prog("file")

	def run_ffprobe(self):
		if self.disableActions_Timer.isActive():
			return
		self.run_prog("ffprobe", "-hide_banner")

	def run_mediainfo(self):
		if self.disableActions_Timer.isActive():
			return
		self.run_prog("mediainfo")

	def run_prog(self, prog, args=None):
		if not self.have_program(prog):
			pkg = self.progPackages.get(prog)
			if pkg:
				self._opkgArgs = ("install", pkg)
				self.session.openWithCallback(self.doOpkgCB, MessageBox, _("Program '%s' needs to be installed to run this action.\nInstall the '%s' package to install the program?") % (prog, pkg), type=MessageBox.TYPE_YESNO, default=True)
			else:
				self.session.open(MessageBox, _("Program '%s' not installed.\nThe package containing this program isn't known.") % (prog, how_to), type=MessageBox.TYPE_ERROR, close_on_any_key=True)
			return

		filename = self.SOURCELIST.getFilename()

		if filename is None:
			self.session.open(MessageBox, _("It is not possible to run '%s' on <List of Storage Devices>") % prog, type=MessageBox.TYPE_ERROR)
			return

		if filename.startswith("/"):
			if prog != "file":
				self.session.open(MessageBox, _("You can't usefully run '%s' on a directory.") % prog, type=MessageBox.TYPE_ERROR, close_on_any_key=True)
				return
			filepath = filename
			filename = os.path.basename(os.path.normpath(filepath)) or '/'
			filetype = "directory"
		else:
			sourceDir = self.SOURCELIST.getCurrentDirectory()
			__, filetype = os.path.splitext(filename.lower())
			filepath = os.path.join(sourceDir, filename)
		if prog == "file" or filetype == ".ts" or filetype in MOVIE_EXTENSIONS:
			if args is None:
				args = ()
			elif not isinstance(args, (tuple, list)):
				args = (args,)
			toRun = (prog,) + tuple(args) + (filepath,)
			self._progConsole = self.session.open(Console, cmdlist=(toRun,), finishedCallback=self.progConsoleCB)
		else:
			self.session.open(MessageBox, _("You can't usefully run '%s' on '%s'.") % (prog, filename), type=MessageBox.TYPE_ERROR, close_on_any_key=True)

	def progConsoleCB(self):
		if hasattr(self, "_progConsole") and "text" in self._progConsole:
			self._progConsole["text"].setPos(0)
			self._progConsole["text"].updateScrollbar()

	def help_run_file(self):
		if self.disableActions_Timer.isActive():
			return
		return self.help_run_prog("file")

	def help_run_ffprobe(self):
		if self.disableActions_Timer.isActive():
			return
		return self.help_run_prog("ffprobe")

	def help_run_mediainfo(self):
		if self.disableActions_Timer.isActive():
			return
		return self.help_run_prog("mediainfo")

	def help_run_prog(self, prog):
		if self.have_program(prog):
			return _("Run '%s' command") % prog
		else:
			if prog in self.progPackages:
				return _("Install '%s' and enable this operation") % prog
			else:
				return _("'%s' not installed and no known package") % prog

	def uninstall_file(self):
		self.uninstall_prog("file")

	def uninstall_ffprobe(self):
		self.uninstall_prog("ffprobe")

	def uninstall_mediainfo(self):
		self.uninstall_prog("mediainfo")

	def uninstall_prog(self, prog):
		if self.have_program(prog):
			pkg = self.progPackages.get(prog)
			if pkg:
				self._opkgArgs = ("remove", pkg)
				self.session.openWithCallback(self.doOpkgCB, MessageBox, _("Program '%s' needs to be installed to run the '%s' action.\nUninstall the '%s' package to uninstall the program?") % (prog, prog, pkg), type=MessageBox.TYPE_YESNO, default=True)
				return True
			else:
				self.session.open(MessageBox, _("Program '%s' is installed.\nThe package containing this program isn't known, so it can't be uninstalled.") % (prog, how_to), type=MessageBox.TYPE_ERROR, close_on_any_key=True)
		return False

	def doOpkgCB(self, ans):
		if ans and hasattr(self, "_opkgArgs"):
			self.session.open(Console, cmdlist=((("opkg",) + self._opkgArgs),))
			del self._opkgArgs

	def help_uninstall_file(self):
		return self.help_uninstall_prog("file")

	def help_uninstall_ffprobe(self):
		return self.help_uninstall_prog("ffprobe")

	def help_uninstall_mediainfo(self):
		return self.help_uninstall_prog("mediainfo")

	def help_uninstall_prog(self, prog):
		if self.have_program(prog):
			pkg = self.progPackages.get(prog)
			if pkg:
				return _("Uninstall '%s' package and disable '%s'") % (pkg, prog)
		return None

	def run_hashes(self):
		if not config.plugins.filecommander.hashes.value:
			self.session.open(MessageBox, _("No hash calculations configured"), type=MessageBox.TYPE_ERROR, close_on_any_key=True)
			return
		progs = tuple((h, self.hashes[h]) for h in config.plugins.filecommander.hashes.value if h in self.hashes and self.have_program(self.hashes[h]))
		if not progs:
			self.session.open(MessageBox, _("None of the hash programs for the hashes %s are available") % ''.join(config.plugins.filecommander.hashes.value), type=MessageBox.TYPE_ERROR, close_on_any_key=True)
			return
		filename = self.SOURCELIST.getFilename()

		if filename is None:
			self.session.open(MessageBox, _("It is not possible to calculate hashes on <List of Storage Devices>"), type=MessageBox.TYPE_ERROR)
			return

		if filename.startswith("/"):
			self.session.open(MessageBox, _("The hash of a directory can't be calculated."), type=MessageBox.TYPE_ERROR, close_on_any_key=True)
			return
		sourceDir = self.SOURCELIST.getCurrentDirectory()
		filepath = os.path.join(sourceDir, filename)
		toRun = []
		for prog in progs:
			toRun += [("echo", "-n", prog[0] + ": "), (prog[1], filepath)]
		self.session.open(Console, cmdlist=toRun)

	def play_music(self, dirsource):
		self.sourceDir = dirsource
		askList = [(_("Play title"), "SINGLE"), (_("Play folder"), "LIST"), (_("Cancel"), "NO")]
		self.session.openWithCallback(self.do_play_music, ChoiceBox, title=_("What do you want to play?\n" + self.sourceDir.getFilename()), list=askList)

	def do_play_music(self, answer):
		longname = self.sourceDir.getCurrentDirectory() + self.sourceDir.getFilename()
		answer = answer and answer[1]
		if answer == "SINGLE":
			fileRef = eServiceReference(eServiceReference.idServiceMP3, eServiceReference.noFlags, longname)
			self.session.open(MoviePlayer, fileRef)
		elif answer == "LIST":
			self.music_playlist()

	def music_playlist(self):
		fileList = []
		from Plugins.Extensions.MediaPlayer.plugin import MediaPlayer
		self.beforeService = self.session.nav.getCurrentlyPlayingServiceReference()
		path = self.sourceDir.getCurrentDirectory()
		mp = self.session.open(MediaPlayer)
		mp.callback = self.cbmusic_playlist
		mp.playlist.clear()
		mp.savePlaylistOnExit = False
		i = 0
		start_song = -1
		filename = self.sourceDir.getFilename()
		fileList = self.sourceDir.getFileList()
		for x in fileList:
			l = len(x)
			if x[0][0] is not None:
				testFileName = x[0][0].lower()
				_, filetype = os.path.splitext(testFileName)
			else:
				testFileName = x[0][0]  # "empty"
				filetype = None
			if l == 3 or l == 2:
				if not x[0][1]:
					if filetype in AUDIO_EXTENSIONS:
						if filename == x[0][0]:
							start_song = i
						i += 1
						mp.playlist.addFile(eServiceReference(4097, 0, path + x[0][0]))
			elif l >= 5:
				testFileName = x[4].lower()
				_, filetype = os.path.splitext(testFileName)
				if filetype in AUDIO_EXTENSIONS:
					if filename == x[0][0]:
						start_song = i
					i += 1
					mp.playlist.addFile(eServiceReference(4097, 0, path + x[4]))
		if start_song < 0:
			start_song = 0
		mp.changeEntry(start_song)
		mp.switchToPlayList()

	def cbmusic_playlist(self, data=None):
		if self.beforeService is not None:
			self.session.nav.playService(self.beforeService)
			self.beforeService = None

	def cbShowPicture(self, idx=0):
		if idx > 0:
			self.SOURCELIST.moveToIndex(idx)

	def onFileAction(self, dirsource, dirtarget):
		filename = dirsource.getFilename()
		self.SOURCELIST = dirsource
		self.TARGETLIST = dirtarget
		sourceDir = dirsource.getCurrentDirectory()
		if not sourceDir.endswith("/"):
			sourceDir = sourceDir + "/"
		testFileName = filename.lower()
		filetype = os.path.splitext(testFileName)[1]
		longname = sourceDir + filename
		print "[Filebrowser]:", filename, sourceDir, testFileName
		if not fileExists(longname):
			self.session.open(MessageBox, _("File not found: %s") % longname, type=MessageBox.TYPE_ERROR)
			return
		if filetype == ".ipk":
			self.session.openWithCallback(self.onFileActionCB, ipkMenuScreen, self.SOURCELIST, self.TARGETLIST)
		elif filetype == ".ts":
			fileRef = eServiceReference(eServiceReference.idDVB, eServiceReference.noFlags, longname)
			self.session.open(MoviePlayer, fileRef)
		elif filetype in MOVIE_EXTENSIONS:
			fileRef = eServiceReference(eServiceReference.idServiceMP3, eServiceReference.noFlags, longname)
			self.session.open(MoviePlayer, fileRef)
		elif filetype in DVD_EXTENSIONS:
			if DVDPlayerAvailable:
				self.session.open(DVD.DVDPlayer, dvd_filelist=[longname])
		elif filetype in AUDIO_EXTENSIONS:
			self.play_music(self.SOURCELIST)
		elif filetype == ".rar" or re.search('\.r\d+$', filetype):
			self.session.openWithCallback(self.onFileActionCB, RarMenuScreen, self.SOURCELIST, self.TARGETLIST)
		elif testFileName.endswith(".tar.gz") or filetype in (".tgz", ".tar"):
			self.session.openWithCallback(self.onFileActionCB, TarMenuScreen, self.SOURCELIST, self.TARGETLIST)
		elif filetype == ".gz":  # Must follow test for .tar.gz
			self.session.openWithCallback(self.onFileActionCB, GunzipMenuScreen, self.SOURCELIST, self.TARGETLIST)
		elif filetype == ".zip":
			self.session.openWithCallback(self.onFileActionCB, UnzipMenuScreen, self.SOURCELIST, self.TARGETLIST)
		elif filetype in IMAGE_EXTENSIONS:
			if self.SOURCELIST.getSelectionIndex() != 0:
				self.session.openWithCallback(
					self.cbShowPicture,
					ImageViewer,
					self.SOURCELIST.getFileList(),
					self.SOURCELIST.getSelectionIndex(),
					self.SOURCELIST.getCurrentDirectory(),
					filename
				)
		elif filetype in (".sh", ".py", ".pyo"):
			self.run_script(self.SOURCELIST, self.TARGETLIST)
		elif filetype == ".mvi":
			self.file_name = longname
			self.tmp_file = '/tmp/grab_%s_mvi.png' %filename[:-4]
			choice = [(_("No"), "no"),
					(_("Show as Picture (press any key to close)"), "show")]
			savetext = ''
			stat = os.statvfs('/tmp/')
			if stat.f_bavail * stat.f_bsize > 1000000:
				choice.append((_("Show as Picture and save as file ('%s')")%self.tmp_file , "save"))
				savetext = _(" or save additional the picture to a file")
			self.session.openWithCallback(self.mviFileCB, MessageBox, _("Show '%s' as picture%s?\nThe current service must interrupted!") %(longname,savetext), simple=True, list=choice)
		elif filetype in TEXT_EXTENSIONS or config.plugins.filecommander.unknown_extension_as_text.value:
			try:
				xfile = os.stat(longname)
			except OSError as oe:
				self.session.open(MessageBox, _("%s: %s") % (longname, oe.strerror), type=MessageBox.TYPE_ERROR)
				return
			if (xfile.st_size < 1000000):
				self.session.open(vEditor, longname)
				self.onFileActionCB(True)
		else:
			try:
				found_viewer = openFile(self.session, guess_type(longname)[0], longname)
			except TypeError, e:
				found_viewer = False
			if not found_viewer:
				self.session.open(MessageBox, _("No viewer installed for this file type: %s") % filename, type=MessageBox.TYPE_ERROR, timeout=5, close_on_any_key=True)
Ejemplo n.º 4
0
class FileCommanderFileStatInfo(Screen, stat_info):
	skin = """
		<screen name="FileCommanderFileStatInfo" backgroundColor="un44000000" position="center,center" size="545,345" title="File/Directory Status Information">
			<widget name="filename" position="10,0" size="525,46" font="Regular;20"/>
			<widget source="list" render="Listbox" position="10,60" size="525,275" scrollbarMode="showOnDemand" selectionDisabled="1" transparent="1" >
				<convert type="TemplatedMultiContent">
					{"template": [
						# 0   100 200 300 400 500
						# |   |   |   |   |   |
						# 00000000 1111111111111
						MultiContentEntryText(pos = (0, 0), size = (200, 25), font = 0, flags = RT_HALIGN_LEFT, text = 0), # index 0 is a label
						MultiContentEntryText(pos = (225, 0), size = (300, 25), font = 0, flags = RT_HALIGN_LEFT, text = 1), # index 1 is the information
						],
						"fonts": [gFont("Regular", 20)],
						"itemHeight": 25,
						"selectionEnabled": False
					}
				</convert>
			</widget>
		</screen>
	"""

	SIZESCALER = UnitScaler(scaleTable=UnitMultipliers.Iec, maxNumLen=3, decimals=1)

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

		self.list = []

		self["list"] = List(self.list)
		self["filename"] = Label()
		self["link_sep"] = Label()
		self["link_label"] = Label()
		self["link_value"] = Label()

		self["link_sep"].hide()

		self["actions"] = ActionMap(
			["SetupActions", "DirectionActions"],
			{
				"cancel": self.close,
				"ok": self.close,
				"up": self.pageUp,
				"down": self.pageDown,
			}, prio=-1)

		self.source = source

		self.onShown.append(self.fillList)

	def pageUp(self):
		if "list" in self:
			self["list"].pageUp()

	def pageDown(self):
		if "list" in self:
			self["list"].pageDown()

	def fillList(self):
		filename = self.source.getFilename()
		sourceDir = self.source.getCurrentDirectory()

		if filename is None:
			self.session.open(MessageBox, _("It is not possible to get the file status of <List of Storage Devices>"), type=MessageBox.TYPE_ERROR)
			self.close()
			return

		if filename.endswith("/"):
			filepath = os.path.normpath(filename)
			if filepath == '/':
				filename = '/'
			else:
				filename = os.path.normpath(filename)
		else:
			filepath = os.path.join(sourceDir, filename)

		filename = os.path.basename(os.path.normpath(filename))
		self["filename"].text = filename
		self.list = []

		try:
			st = os.lstat(filepath)
		except OSError as oe:
			self.session.open(MessageBox, _("%s: %s") % (filepath, oe.strerror), type=MessageBox.TYPE_ERROR)
			self.close()
			return

		mode = st.st_mode
		perms = stat.S_IMODE(mode)
		self.list.append((_("Type:"), self.filetypeStr(mode)))
		self.list.append((_("Owner:"), "%s (%d)" % (self.username(st.st_uid), st.st_uid)))
		self.list.append((_("Group:"), "%s (%d)" % (self.groupname(st.st_gid), st.st_gid)))
		self.list.append((_("Permissions:"), _("%s (%04o)") % ( self.fileModeStr(perms), perms)))
		if not (stat.S_ISCHR(mode) or stat.S_ISBLK(mode)):
			self.list.append((_("Size:"), "%s (%sB)" % ("{:n}".format(st.st_size), ' '.join(self.SIZESCALER.scale(st.st_size)))))
		self.list.append((_("Modified:"), self.formatTime(st.st_mtime)))
		self.list.append((_("Accessed:"), self.formatTime(st.st_atime)))
		self.list.append((_("Metadata changed:"), self.formatTime(st.st_ctime)))
		self.list.append((_("Links:"), "%d" % st.st_nlink))
		self.list.append((_("Inode:"), "%d" % st.st_ino))
		self.list.append((_("On device:"), "%d, %d" % ((st.st_dev >> 8) & 0xff, st.st_dev & 0xff)))

		self["list"].updateList(self.list)

		if stat.S_ISLNK(mode):
			self["link_sep"].show()
			self["link_label"].text = _("Link target:")
			try:
				self["link_value"].text = os.readlink(filepath)
			except OSError as oe:
				self["link_value"].text = _("Can't read link contents: %s") % oe.strerror
		else:
			self["link_sep"].hide()
			self["link_label"].text = ""
			self["link_value"].text = ""
Ejemplo n.º 5
0
	def buildMovieListEntry(self, serviceref, info, begin, data):
		switch = config.usage.show_icons_in_movielist.value
		width = self.l.getItemSize().width()
		dateWidth = self.dateWidth
		if config.usage.time.wide.value:
			dateWidth = int(dateWidth * 1.15)
		if not config.movielist.use_fuzzy_dates.value:
			dateWidth += 35
		showLen = self.showCol(config.movielist.showlengths, self.COL_LENGTH)
		lenWidth = self.lenWidth if showLen else 0
		showSize = self.showCol(config.movielist.showsizes, self.COL_SIZE)
		sizeWidth = self.sizeWidth if showSize else 0
		markSize = self.markWidth
		iconSize = self.iconsWidth
		space = self.spaceIconeText
		r = self.spaceRight
		ih = self.itemHeight
		pathName = serviceref.getPath()
		res = [None]

		res.append(MultiContentEntryPixmapAlphaBlend(pos=(self.listPos - markSize - space, self.markShift), size=(markSize, self.iconMarked[0].size().height()), png=self.iconMarked[self.getCurrent() in self.markList]))
		iconPos = self.listPos
		textPos = iconPos + iconSize + space

		if serviceref.flags & eServiceReference.mustDescent:
			# Directory
			# Name is full path name
			if info is None:
				# Special case: "parent"
				txt = ".."
			else:
				txt = os.path.basename(os.path.normpath(pathName))
			if txt == ".Trash":
				res.append(MultiContentEntryPixmapAlphaBlend(pos=(iconPos, self.trashShift), size=(iconSize, self.iconTrash.size().height()), png=self.iconTrash))
				res.append(MultiContentEntryText(pos=(textPos, 0), size=(width - textPos - dateWidth - r, ih), font=0, flags=RT_HALIGN_LEFT | RT_VALIGN_CENTER, text = _("Trash")))
				res.append(MultiContentEntryText(pos=(width - dateWidth - r, 0), size=(dateWidth, ih), font=1, flags=RT_HALIGN_RIGHT | RT_VALIGN_CENTER, text=_("Trash")))
				return res
			res.append(MultiContentEntryPixmapAlphaBlend(pos=(iconPos, self.dirShift), size=(iconSize, iconSize), png=self.iconFolder))
			res.append(MultiContentEntryText(pos=(textPos, 0), size=(width - textPos - dateWidth - r, ih), font=0, flags = RT_HALIGN_LEFT | RT_VALIGN_CENTER, text=txt))
			res.append(MultiContentEntryText(pos=(width - dateWidth - r, 0), size=(dateWidth, ih), font=1, flags=RT_HALIGN_RIGHT | RT_VALIGN_CENTER, text=_("Directory")))
			return res
		if data == -1 or data is None:
			data = MovieListData()
			cur_idx = self.l.getCurrentSelectionIndex()
			x = self.list[cur_idx]  # x = ref,info,begin,...
			data.len = info.getLength(serviceref)
			if showSize:
				data.size = info.getFileSize(serviceref)
			self.list[cur_idx] = (x[0], x[1], x[2], data)  # update entry in list... so next time we don't need to recalc
			data.txt = info.getName(serviceref)
			if config.movielist.hide_extensions.value:
				fileName, fileExtension = os.path.splitext(data.txt)
				if fileExtension in KNOWN_EXTENSIONS:
					data.txt = fileName
			data.icon = None
			data.part = None
			if os.path.basename(pathName) in self.runningTimers:
				if switch == 'i':
					if (self.playInBackground or self.playInForeground) and serviceref == (self.playInBackground or self.playInForeground):
						data.icon = self.iconMoviePlayRec
					else:
						data.icon = self.iconMovieRec
				elif switch in ('p', 's'):
					data.part = 100
					if (self.playInBackground or self.playInForeground) and serviceref == (self.playInBackground or self.playInForeground):
						data.partcol = self.pbarColourSeen
						data.partcolsel = self.pbarColourSeenSel
					else:
						data.partcol = self.pbarColourRec
						data.partcolsel = self.pbarColourRecSel
			elif (self.playInBackground or self.playInForeground) and serviceref == (self.playInBackground or self.playInForeground):
				data.icon = self.iconMoviePlay
			else:
				data.part = moviePlayState(pathName + '.cuts', serviceref, data.len * 90000)
				if switch == 'i':
					if data.part is not None and data.part >= 0:
						data.icon = self.iconPart[data.part // 25]
					else:
						if config.usage.movielist_unseen.value:
							data.icon = self.iconUnwatched
				elif switch in ('p', 's'):
					if data.part is not None and data.part > 0:
						data.partcol = self.pbarColourSeen
						data.partcolsel = self.pbarColourSeenSel
					else:
						if config.usage.movielist_unseen.value:
							data.part = 100
							data.partcol = self.pbarColour
							data.partcolsel = self.pbarColourSel
		if showLen:
			len = data.len
			len = "%d:%02d" % (len / 60, len % 60) if len > 0 else ""
		if showSize:
			size = _("%s %sB") % UnitScaler()(data.size) if data.size > 0 else ""

		if data:
			if switch == 'i' and hasattr(data, 'icon') and data.icon is not None:
				if self.partIconeShift is None:
					partIconeShift = max(0, int((ih - data.icon.size().height()) / 2))
				else:
					partIconeShift = self.partIconeShift
				pos = (iconPos, partIconeShift)
				res.append(MultiContentEntryPixmapAlphaBlend(pos=pos, size=(iconSize, data.icon.size().height()), png=data.icon))
			elif switch in ('p', 's'):
				if switch == 'p':
					iconSize = self.pbarLargeWidth
					textPos = iconPos + iconSize + space
				if hasattr(data, 'part') and data.part > 0:
					res.append(MultiContentEntryProgress(pos=(iconPos, self.pbarShift), size=(iconSize, self.pbarHeight), percent=data.part, borderWidth=2, foreColor=data.partcol, foreColorSelected=data.partcolsel, backColor=None, backColorSelected=None))
				elif hasattr(data, 'icon') and data.icon is not None:
					res.append(MultiContentEntryPixmapAlphaBlend(pos=(iconPos, self.pbarShift), size=(iconSize, self.pbarHeight), png=data.icon))

		begin_string = ""
		if begin > 0:
			if config.movielist.use_fuzzy_dates.value:
				begin_string = ' '.join(FuzzyTime(begin, inPast = True))
			else:
				begin_string = strftime("%s %s" % (config.usage.date.daylong.value, config.usage.time.short.value), localtime(begin))

		textItems = []
		xPos = width

		if showSize:
			xPos -= sizeWidth + r
			textItems.insert(0, MultiContentEntryText(pos=(xPos, 0), size=(sizeWidth, ih), font=1, flags=RT_HALIGN_RIGHT | RT_VALIGN_CENTER, text=size))
		if showLen:
			xPos -= lenWidth + r
			textItems.insert(0, MultiContentEntryText(pos=(xPos, 0), size=(lenWidth, ih), font=1, flags=RT_HALIGN_RIGHT | RT_VALIGN_CENTER, text=len))
		xPos -= dateWidth + r
		textItems.insert(0, MultiContentEntryText(pos=(xPos, 0), size=(dateWidth, ih), font=1, flags=RT_HALIGN_RIGHT | RT_VALIGN_CENTER, text=begin_string))
		textItems.insert(0, MultiContentEntryText(pos=(textPos, 0), size=(xPos - textPos, ih), font=0, flags=RT_HALIGN_LEFT | RT_VALIGN_CENTER, text=data.txt))

		res += textItems
		return res
Ejemplo n.º 6
0
	def convertSize(self, size):
		return _("%s %sB") % UnitScaler()(size)