# -*- coding: utf-8 -*-

#-------------------------------Backgroundfunction-----------------------------------------
F_SWAP_ON=1
F_RW_SPEED=2
#--------------------------------Browser---------------------------------------------------
GMEDIASCAN = "/usr/bin/gMediaScan"
#GMEDIASCAN = "/root/bin/gMediaScan"
DMCONFFILE="/etc/enigma2/gemini_DateiBrowser.conf"
PINCODEOFF="0000"


#Fuer B_STATUS
STATUS_INFO=1
STATUS_PICTURE=2
STATUS_PROTECT=4
STATUS_MARKET=8

#Info-Positionen in den Dateien
SOUND_TIME = MOVIE_COUNTRY = PICTURE_MAKE = 0
SOUND_TITLE = MOVIE_GENRE = PICTURE_MODEL = 1
SOUND_ARTIST = MOVIE_RATING = PICTURE_DATE = 2
SOUND_ALBUM = MOVIE_DATE = PICTURE_SIZE = 3
SOUND_GENRE = MOVIE_DESC = 4
SOUND_DATE = MOVIE_TITLE = 5
SOUND_FILE = MOVIE_COVER = 6
MOVIE_ID = 7

from gLocale import _
from GeminiDef import *

from WidgetVariableList import WidgetVariableList
from gTools import libgeminimain, cleanexit, ctoolsclass, gLoadPixmap, pathExists, pathRemove, modulExists, Jukeboxfound, Torrentfound, PDFfound, reReadPluginList, geminiarchiver, DEFAULTGEMINICACHEDIR
from plugin import cgevent, geventNotifier
from WidgetConfig import WidgetInput
from WidgetTools import errorlist, C_DELETE, C_COPY, C_MOVE, C_EXTRACT, C_MAKE_ARCHIVE, BackGroundThread, searchMovieExtension, SetPermission, GetPermission, CreateSymlink, CreateDir, CreateFile, HumanSize, getPackInfo, SetNewName, getDirInfo, DVDBD_Player

from enigma import eTimer
from Tools.BoundFunction import boundFunction
from Components.ActionMap import NumberActionMap
from Screens.InfoBarGenerics import InfoBarCueSheetSupport
from Screens.ChoiceBox import ChoiceBox
from Screens.MessageBox import MessageBox
from Components.Console import Console as cConsole
from Components.config import config

from os import readlink, path as os_path

#-----------------------------------------------------------------------------------------------------

def readCacheInfos(cfile):
	list = []
	try:
		if pathExists(cfile):
			file = open(cfile, 'r')
			lines = file.readlines()
			file.close()
			for x in lines:
				list.append(x.strip())
	except:
		pass
	if len(list)==4 or len(list)==5:#bei pics und movies
		return list
	elif len(list)==7:#bei sound
		list[0] = int(list[0])#Zeit in Int
		return list
	return []

def createInfoString(info, entry, forceName=True):
	text=""
	if forceName:
		text = entry[B_NAME]

	if entry[B_FILTER] & FILTER_SOUND and len(info):
		time = ""
		if info[SOUND_TIME]>0:
			time = "("+libgeminimain.getHumanDate(1,info[SOUND_TIME])+") "
		elif entry[B_FILTER] & FILTER_SOUND and forceName:
			time = "(0:00) "

		if info[SOUND_TITLE] != "":
			text = info[SOUND_TITLE]
		if info[SOUND_ARTIST] != "":
			text += "\n" + info[SOUND_ARTIST]
		if info[SOUND_ALBUM] != "":
			text += "\n" + info[SOUND_ALBUM]
			if info[SOUND_DATE] != "" and info[SOUND_DATE] != "0":
				text += " (" + info[SOUND_DATE] + ")"
		return time + text
	elif entry[B_FILTER] & FILTER_PICS and len(info):
		text += _("Camera") + ": "
		if info[PICTURE_MODEL]=="unknown":
			text += _(info[PICTURE_MODEL])
		else:
			text += info[PICTURE_MODEL]
		text += "\n" + _("Size") + ": " + info[PICTURE_SIZE]
		text += "\n" + _("Date") + ": "
		if info[PICTURE_DATE]=="":
			text += libgeminimain.getHumanDate(3,entry[B_DATE])
		else:
			text += info[PICTURE_DATE]
	elif entry[B_FILTER] & FILTER_MOVIES and len(info):
		if info[MOVIE_COUNTRY] != "":
			text += _("Country") + ": " + info[MOVIE_COUNTRY]
			if info[MOVIE_DATE] != "":
				text += " (" + info[MOVIE_DATE] + ")"
		else:
			if info[MOVIE_DATE] != "":
				text += _("Date") + ": " + info[MOVIE_DATE]
		if len(info)==4:
			text += "\n" + _("Rating") + ": " + info[MOVIE_RATING]
			if info[MOVIE_GENRE] != "":
				text += "\n" + _("Genre") + ": " + info[MOVIE_GENRE]
		else:
			if info[MOVIE_GENRE] != "":
				text += "   " + _("Genre") + ": " + info[MOVIE_GENRE]
			text += "\n" + info[MOVIE_DESC]
	return text

def readDMconf():
	hiddelist = []
	permlist = []
	try:
		ishidelist=True
		rfile = open(DMCONFFILE, 'r')
		for x in rfile.readlines():
			val = x.strip()
			if val=="::::":
				ishidelist=False
			else:
				if ishidelist:
					hiddelist.append(val)
				else:
					permlist.append(val)
		rfile.close()
	except:
		pass
	return hiddelist, permlist

#-----------------------------------------------------------------------------------------------------

class gBrowser(WidgetVariableList):
	def __init__(self, session, name=None, setPath=None, filter=FILTER_NONE):
		self.filter = filter
		bluename = None
		if self.filter == FILTER_NONE:
			bluename = _("Mode")

		WidgetVariableList.__init__ (self, session, name or _("File Browser"), showMenuPix=True, showInfoPix=True, NameBlue=bluename, icon="icon_filebrowser.png")
		
		self.__largeString=""
		if cgevent.getConfig("Dmanager_largeview",1)==1:
			self.__largeString="big"
			
		if self.__largeString=="big":
			self.skinName = ["VariableListCover_" + self.__class__.__name__, "VariableListCover"]
		else:
			self.skinName = ["VariableList4ButtonSmallIcon_" + self.__class__.__name__, "VariableList4ButtonSmallIcon"]
		
		self["NumberActions"] = NumberActionMap(["NumberActions"],
		{
			"0": self.Key0
		}, -1)
		
		self.ListTimer = eTimer()
		self.ListTimer_conn = self.ListTimer.timeout.connect(self.__UpdateEntry)
		self.Console = cConsole()
		self.__ConsoleRunning = False
		self.__newDMconf = False
		self.__hidelist, self.__permlist = readDMconf()
		
		
		if setPath == None:
			self.path = cgevent.getConfig("Dmanager_StartDir"," ")
			if self.path == " ":
				self.path = cgevent.getConfig("Dmanager_lastpath","/")
		else:
			self.path = setPath
		if self.path == "":
			self.path = "/"

		self.lastpath = self.path
		self.path = os_path.dirname(self.path)
		self.__lastEvent=0

		self.__loadConfig()
		geventNotifier.append((EVENT_BACKGROUND, self.__newBG_Event))
		if self.filter == FILTER_NONE and cgevent.getConfig("Dmanager_startfirst",0)==1:
			self.onFirstExecBegin.append(self.__startFavoMode)
		elif self.filter == FILTER_NONE and cgevent.getConfig("Dmanager_startfirst",0)==2:
			self.onFirstExecBegin.append(self.__starteCommander)
		else:
			self.onLayoutFinish.append(self.__onLayoutFinish)
		
	def KeyExit(self):
		geventNotifier.remove((EVENT_BACKGROUND, self.__newBG_Event))
		if self.filter == FILTER_NONE:
			sel = self.getCurrentEntry()
			if sel and sel[3]:
				if sel[3][B_FILTER]  & FILTER_GOUP:
					cgevent.setConfig("Dmanager_lastpath", self.path + "/..")
				else:
					cgevent.setConfig("Dmanager_lastpath", sel[3][B_FULL])
		
		self.__writeDMconf()
		self.Console.killAll()
		self.close()
		#cleanexit(__name__)
		
	def __onLayoutFinish(self):
		if self.filter == FILTER_NONE:
			self.SetRB(_("Command"))
		self.ShowHideInfoIcon(False)
		self.__fillListe()
		
	def Key0(self,number):
		self.SetIndex(0)
		
	def KeyBlue(self):
		if self.filter == FILTER_NONE:
			menu=[]
			menu.append((_("Favourites"), "favo"))
			menu.append(("eCommander", "ecomm"))
			self.session.openWithCallback(self.__modeCallback, ChoiceBox, title=_("Mode"), list=menu)
	
	def __modeCallback(self, what=None):
		if what is None:
			return
			
		if what[1]=="favo":
			self.__startFavoMode()
		elif what[1]=="ecomm":
			sel = self.getCurrentEntry()
			if sel and sel[3]:
				if sel[3][B_FILTER]  & FILTER_GOUP:
					self.__starteCommander(self.path + "/..")
				else:
					self.__starteCommander(sel[3][B_FULL])
			else:
				self.__starteCommander(self.lastpath)
			
	def __startFavoMode(self):
		geventNotifier.remove((EVENT_BACKGROUND, self.__newBG_Event))
		from FileBrowserFavo import BrowserFavo
		self.session.openWithCallback(self.__favoritesCallback, BrowserFavo)
		
	def __starteCommander(self, path=None):
		geventNotifier.remove((EVENT_BACKGROUND, self.__newBG_Event))
		from FileBrowser2Page import eCommander
		self.session.openWithCallback(self.__favoritesCallback, eCommander, path, True)
		
	def __newBG_Event(self, what=0, val=0):
		if what == EVENT_BACKGROUND and val is not None:
			try:
				if val & (BG_DELETE | BG_EXTRACT | BG_COPYMOVE):
					self.setTitle("* " + _("Path") + ": " + self.path)
					self.__lastEvent = val
				elif self.__lastEvent>0:
					self.setTitle(_("Path") + ": " + self.path)
					if self.__lastEvent & (BG_EXTRACT | BG_COPYMOVE | BG_DELETE):
						self.__lastEvent = 0
						index = self.GetIndex()
						self.__fillListe()
						self.SetIndex(index)
			except:
				pass

	def __fillListe(self):
		flist = libgeminimain.getPyList(GETFILELIST,(self.path, self.filter, self.SortBy, self.__show_ts_help_files, self.__show_system_files, self.__show_ts_info))

		if self.filter == FILTER_NONE and self.__media_scan>0 and self.path and self.path!="/" and self.path!="/media/network" and pathExists(self.path+"/.nomedia")==False:#AutoScan Folder
			self.__startConsole(MI_SCANDIR,None)
		
		#groesse listentry auf default oder aus FolderProp
		#if len(flist) and flist[0][B_FILTER] & FILTER_GOUP and flist[0][B_EXT] != "":
		#	if flist[0][B_EXT]=="bigList":
		#		self.__setListHeigth(1)
		#	else:
		#		self.__setListHeigth(0)
		#else:
		#	self.__setListHeigth(self.__largeView)
		
		largeView=0
		if self.__largeString=="big":
			largeView=1

		list = []
		index = 0
		count = 0
		for x in flist:
			if x[B_NAME] in self.__hidelist:
				continue
			
			if x[B_FULL] in self.__permlist and config.ParentalControl.folderpin.value != PINCODEOFF:
				x[B_STATUS] |= STATUS_PROTECT

			if x[B_FULL] == self.lastpath:
				index = count

			#Text
			text = x[B_NAME]
			extratext = ""
			if x[B_FILTER] & FILTER_MOVIES:
				#print x
				if x[B_DESC] != "":
					text = x[B_DESC]
				if largeView and x[B_EXT_DESC] != "":
					extratext =  x[B_EXT_DESC]

			if largeView and x[B_FILTER] & (FILTER_SOUND | FILTER_MOVIES | FILTER_PICS | FILTER_ISO):
				extratext += createInfoString(readCacheInfos(x[B_CFILE] + ".txt"),x,False)

			#FilePic
			filePic = None
			if largeView and x[B_CFILE] and pathExists(x[B_CFILE] + ".png"):#Bild im Gemini-Cache suchen
				filePic = gLoadPixmap(x[B_CFILE] + ".png",cached=False)
			elif largeView and x[B_FILTER] & FILTER_DIR and x[B_DESC]!="":#Bild ueber eDirectory festgelegt
				filePic = gLoadPixmap(x[B_DESC])
			elif largeView and x[B_FILTER] & FILTER_DVD:
				filePic = gLoadPixmap("bigext_folder_dvd.png")
			else:
				filePic = gLoadPixmap(self.__largeString + x[B_PICTURE])

			#extraPics
			extraPic = None
			if x[B_STATUS] & STATUS_PROTECT:
				extraPic = gLoadPixmap(self.__largeString + "logo_protect.png")
			elif x[B_FILTER] & FILTER_LINK:
				extraPic = gLoadPixmap(self.__largeString + "logo_link.png")
			elif x[B_FILTER] & FILTER_TS:
				LastPlayed=False
				for cuts in cgevent.GetCutsList(x[B_FULL]+".cuts"):
					if cuts[1]==InfoBarCueSheetSupport.CUT_TYPE_LAST:
						LastPlayed=True
						break
				if LastPlayed==False:
					extraPic = gLoadPixmap(self.__largeString + "logo_new.png")

			if largeView:
				list.append((text, filePic, extraPic, x, ctoolsclass.getSeperatorPic(), extratext, None))
			else:
				list.append((text, filePic, extraPic, x))
			count += 1

		self.setTitle(_("Path") + ": " + self.path)
		self.SetList(list)
		self.SetIndex(index)

	def selectionChanged(self):
		self.ListTimer.start(300,True)
		
	def __UpdateEntry(self):
		sel = self.getCurrentEntry()

		self.SetLabel()
		self.SetGB()
		self.ShowHideInfoIcon(False)
		iconpic=None
		
		if sel and sel[3]:
			#status label
			if sel[3][B_FILTER] & FILTER_GOUP:
				if sel[3][B_SIZE]>0:
					text = _("%s free of %s") %(HumanSize(sel[3][B_DATE]), HumanSize(sel[3][B_SIZE]))
					if sel[3][B_SIZE] >= sel[3][B_DATE]:
						proz = (100 * sel[3][B_DATE]) / sel[3][B_SIZE]
						if proz >= 0 and proz <= 100:
							text += " (%d%%)" %proz
					self.SetLabel(text) 
			elif sel[3][B_FILTER] & FILTER_LINK:
				self.SetLabel("> " + readlink(sel[3][B_FULL]))
			elif sel[3][B_FILTER] & FILTER_FILE:
				self.SetLabel(libgeminimain.getHumanSize(sel[3][B_SIZE]) + ", " + libgeminimain.getHumanDate(3,sel[3][B_DATE]) + ", " + GetPermission(sel[3][B_MODE]))
				
			cachefile = sel[3][B_CFILE] + ".png"

			#green and info button
			if self.filter == FILTER_NONE:
				self.SetYB(_("Update"))
				if sel[3][B_FILTER] & FILTER_PICS:
					if self.__largeString=="" and pathExists(cachefile):
						iconpic=cachefile
					self.SetGB(_("Show"))
					self.ShowHideInfoIcon(True)
				elif sel[3][B_FILTER] & FILTER_SOUND:
					self.ShowHideInfoIcon(True)
					if Jukeboxfound:
						self.SetGB("Jukebox")
					if self.__largeString=="" and pathExists(cachefile):
						iconpic=cachefile
				elif sel[3][B_FILTER] & (FILTER_ISO | FILTER_DVD):
					self.SetGB(_("Start"))
					if sel[3][B_FILTER] & FILTER_ISO:
						self.ShowHideInfoIcon(True)
					if self.__largeString=="" and pathExists(cachefile):
						iconpic=cachefile
				elif sel[3][B_FILTER] & FILTER_MOVIES:
					self.SetGB(_("Play"))
					self.ShowHideInfoIcon(True)
					if self.__largeString=="" and pathExists(cachefile):
						iconpic=cachefile
				elif sel[3][B_FILTER] & FILTER_SCRIPTE:
					self.SetGB(_("Execute"))
					if sel[3][B_SIZE] < VIEWMAXSIZE:
						self.ShowHideInfoIcon(True)
				elif sel[3][B_FILTER] & FILTER_PL:
					if Jukeboxfound:
						self.SetGB("Jukebox")
				elif sel[3][B_FILTER] & FILTER_TORRENT:
					if Torrentfound:
						self.SetGB("eTorrent")
				elif sel[3][B_FILTER] & FILTER_PACK:
					self.SetGB(_("Extract"))
					if sel[3][B_EXT] != "LZMA":
						if sel[3][B_EXT]=="RAR":
							if geminiarchiver:
								self.ShowHideInfoIcon(True)
						else:
							self.ShowHideInfoIcon(True)
				elif sel[3][B_FILTER] & FILTER_DIR and not sel[3][B_FILTER] & FILTER_GOUP:
					self.ShowHideInfoIcon(True)
				elif sel[3][B_FILTER] & FILTER_IPK:
					self.SetGB(_("Install"))
					self.ShowHideInfoIcon(True)
				elif sel[3][B_FILTER] & FILTER_PDF:
					if PDFfound:
						self.SetGB(_("Show"))
				elif sel[3][B_FILTER] & FILTER_MVI:
					self.SetGB(_("Show"))
				elif sel[3][B_FILTER] & FILTER_TXT:
					if sel[3][B_SIZE] < VIEWMAXSIZE:
						self.ShowHideInfoIcon(True)
					#if QTEditor:
					#	self.SetGB(_("Edit"))
			else:
				if self.filter & sel[3][B_FILTER]:
					self.SetGB(_("OK"))

		self.SetIcon(iconpic)
			
	def KeyInfo(self): #Informationen
		if self.filter != FILTER_NONE:
			return
		val = self.getCurrentEntry()
		if val and val[3] and not val[3][B_FILTER] & FILTER_GOUP:
			sel = val[3]
			if sel[B_FILTER] & FILTER_DIR:
				self.SetLabel(getDirInfo(sel,self.path))
			elif sel[B_FILTER] & (FILTER_PICS | FILTER_MOVIES | FILTER_SOUND):
				from searchMediaInfo import BrowserFileInfos
				self.session.open(BrowserFileInfos, sel)
			elif sel[B_FILTER] & FILTER_IPK:
				from WidgetIpkg import ipkFileInfo
				info = ipkFileInfo(sel[B_FULL])
				if len(info)>0:
					tmpstr = ""
					for x in info:
						tmpstr += x
					if tmpstr!="":
						self.session.open(MessageBox, tmpstr,MessageBox.TYPE_INFO)
			elif sel[B_FILTER] & (FILTER_TXT | FILTER_SCRIPTE):
				from ShowFileList import ShowFileList
				self.session.open(ShowFileList, sel[B_FULL])
			elif sel[B_FILTER] & FILTER_PACK:
				size = getPackInfo(sel)
				if size>0:
					self.session.open(MessageBox, _("Needed %s disk space.") %HumanSize(size), MessageBox.TYPE_INFO, timeout=5)

	def KeyOk(self):
		sel = self.getCurrentEntry()
		if sel and sel[3]:
			if sel[3][B_FILTER] & FILTER_DIR:
				if sel[3][B_STATUS] & STATUS_PROTECT:
					self.session.openWithCallback(self.__PinCode_Callback, WidgetInput, PinCode=config.ParentalControl.folderpin.value)
				else:
					self.lastpath = self.path
					self.path = sel[3][B_FULL]
					self.__fillListe()
			elif self.__ok_is_green==1:
				self.KeyGreen()

	def KeyGreen(self):
		sel = self.getCurrentEntry()
		if sel and sel[3]:
			if sel[3][B_FILTER] & FILTER_GOUP:
				return
			elif self.filter == FILTER_NONE:
				if sel[3][B_STATUS] & STATUS_PROTECT:
					self.session.openWithCallback(self.__PinCode_Callback, WidgetInput, PinCode=config.ParentalControl.folderpin.value)
				else:
					self.__startFile(sel[3])
			elif self.filter & sel[3][B_FILTER]:
				if sel[3][B_FILTER] & (FILTER_MOVIES | FILTER_SOUND):
					self.close(sel[3])
				else:
					self.close(sel[3][B_FULL])

	def __startFile(self, val):
		try:
			if val[B_FILTER] & (FILTER_DVD | FILTER_ISO):
				DVDBD_Player(self.session,val)
			elif val[B_FILTER] & FILTER_MOVIES:
				self.__writeDMconf()
				self.lastpath = val[B_FULL]
				from gMoviePlayer import ExMoviePlayer
				self.session.openWithCallback(self.__moviePlayerCallback, ExMoviePlayer, val)
			elif val[B_FILTER] & FILTER_SCRIPTE:
				from ShowFileList import ShowFileList
				self.session.open(ShowFileList, cmdlist = [val[B_FULL]])
			elif val[B_FILTER] & FILTER_TORRENT:
				if Torrentfound:
					from Plugins.Bp.geminictorrent.etorrent import etorrent
					self.session.open(etorrent, path=val[B_FULL])
			elif val[B_FILTER] & (FILTER_SOUND | FILTER_PL):
				if Jukeboxfound:
					from Plugins.Bp.geminijukebox.jukebox import JukeBox
					self.session.open(JukeBox, setPath=val[B_FULL])
			elif val[B_FILTER] & FILTER_IPK:
				self.lastpath = val[B_FULL]
				from WidgetIpkg import WidgetIpkg, IPKG_UPDATE, IPKG_INSTALL_LOCAL
				self.session.open(WidgetIpkg, cmdList=[(IPKG_UPDATE,""), (IPKG_INSTALL_LOCAL,val[B_FULL])])
			elif val[B_FILTER] & FILTER_MVI:
				from ShowMVI import ShowMVI
				self.session.open(ShowMVI, val[B_FULL])
			elif val[B_FILTER] & FILTER_PICS:
				piclist=[]
				picindex=0
				index=-1
				for x in self.GetList():
					if x[3][B_FILTER] & FILTER_PICS:
						index += 1
						piclist.append((x[3][B_NAME],x[3][B_FULL]))
						if x[3][B_FULL] == val[B_FULL]:
							picindex = index

				from WidgetShowPicture import gPicPlayer, gPicPlayerThumb
				if len(piclist):
					self.session.openWithCallback(self.__picplayCallback, gPicPlayer, piclist, picindex)
			#elif val[B_FILTER] & FILTER_TXT:
			#	if QTEditor:
			#		from Plugins.Bp.geminiqteditor.editor import Editor
			#		self.session.open(Editor, opt=val[B_FULL])
			elif val[B_FILTER] & FILTER_PDF:
				if PDFfound:
					from Plugins.Bp.geminipdf.gpdf import Cpdf
					self.session.open(Cpdf, path=val[B_FULL], name=val[B_NAME])
				else:
					self.session.open(MessageBox, _("Package '%s' not installed!") %("geminipdf"), MessageBox.TYPE_INFO, timeout=5)
			elif val[B_FILTER] & FILTER_PACK:
				self.__menuCallback((_("Extract package"), "extractpackage", val))
		except Exception, e:
			print "[%s] <%s>"%(__name__,e)
		
	def KeyRed(self):
		val = self.getCurrentEntry()
		if val and val[3]:
			menu = []
			if not val[3][B_FILTER] & FILTER_GOUP and self.filter == FILTER_NONE:
				menu.append((_("Delete"), "delete", val[3]))
				menu.append((_("Copy"), "copy", val[3]))
				menu.append((_("Move"), "move", val[3]))
				menu.append((_("Rename"), "rename", val[3]))
				menu.append((_("Create symlink"),"symlink", val[3]))
				menu.append(("--", "",None))
				if val[3][B_FILTER] & FILTER_DIR:
					menu.append((_("Properties"), "properties", val[3]))
				else:
					menu.append((_("Permission"), "chmod", val[3]))
				if val[3][B_FILTER] & FILTER_FILE and val[3][B_SIZE] < VIEWMAXSIZE:
					menu.append((_("View as Text"), "showfile", val[3]))
				if val[3][B_FILTER] & (FILTER_FILE | FILTER_DIR):
					menu.append(((_("hide '%s'") % val[3][B_NAME]),"hideentry", val[3]))#verstecken
				if val[3][B_FILTER] & FILTER_DIR:
					if val[3][B_STATUS] & STATUS_PROTECT:
						menu.append(((_("unprotect '%s'") % val[3][B_NAME]),"removeProtect", val[3]))#schuetzen
					else:
						menu.append(((_("protect '%s'") % val[3][B_NAME]),"setProtect", val[3]))#schuetzen
				if val[3][B_FILTER] & FILTER_PACK:
					menu.append((_("Extract package"), "extractpackage", val[3]))
				if not val[3][B_FILTER] & FILTER_PACK:
					menu.append((_("Create package"), "createpackage", val[3]))
				self.session.openWithCallback(self.__menuCallback, ChoiceBox, title="", list=menu)

	def KeyMenu(self):
		val = self.getCurrentEntry()
		if val and val[3]:
			menu = []
			#MediaIcon
			if val[3][B_FILTER] & (FILTER_MOVIES | FILTER_SOUND | FILTER_PICS | FILTER_ISO):
				if pathExists(val[3][B_CFILE] + ".png") or pathExists(val[3][B_CFILE] + ".txt"):
					menu.append((_("Delete Media-Infos"), "deleteMediaInfo", val[3]))
				elif self.__ConsoleRunning==False:
					menu.append((_("Search Media-Infos"), "createMediaInfo", val[3]))
					if val[3][B_FILTER] & (FILTER_MOVIES | FILTER_ISO):
						menu.append((_("Select Media-Icon, only JPG-Files"), "selectMediaPic", val[3]))
			if val[3][B_FILTER] & FILTER_DIR and not val[3][B_FILTER] & FILTER_GOUP: 
				menu.append((_("Search Media-Infos in Subdirectorys (in Background)"), "scanSubdirs", val[3]))
			
			if len(menu):
				menu.append(("--", "",None))
			menu.append((_("Create new file"), "newfile", None))
			menu.append((_("Create new directory"), "newdir", None))
			if self.filter == FILTER_NONE:
				menu.append(("--", "",None))
				menu.append((_("Setup"), "setup", val[3]))
			self.session.openWithCallback(self.__menuCallback, ChoiceBox, title="", list=menu)

	def __menuCallback(self, what=None):
		if what is None:
			return
		path = what[2]

		if what[1] == "setup":
			self.lastpath = path[B_FULL]
			from confFileBrowser import BrowserSetup
			self.session.openWithCallback(self.__setupCallback, BrowserSetup, self.__hidelist)
		elif what[1] == "delete":
			self.lastpath = path[B_FULL]
			kwargs={'func': C_DELETE, 'filelist': searchMovieExtension([path])}
			if self.__ask:
				count_f=0
				count_d=0
				if path[B_FILTER] & FILTER_FILE:
					count_f += 1
				if path[B_FILTER] & FILTER_DIR:
					count_d += 1
				BackGroundThread(kwargs, self.session, count_f, count_d)
			else:
				BackGroundThread(kwargs)
			index = self.GetIndex()
			self.__fillListe()
			self.SetIndex(index)
		elif what[1] == "copy" or what[1] == "move":
			from confFileBrowser import CopyMoveSetup
			self.session.openWithCallback(boundFunction(self.__copy_move_Callback,what[1],path), CopyMoveSetup, what[0], what[1], path[B_NAME], self.path)
		elif what[1] == "rename":
			from confFileBrowser import RenameClass
			self.session.openWithCallback(boundFunction(self.__renameCallback, path), RenameClass, what[0], path)
		elif what[1] == "properties":
			from confFileBrowser import FolderProp
			self.session.openWithCallback(boundFunction(self.__FolderPropCallback,path), FolderProp, what[0], path, libgeminimain.getPyList(GETFOLDERPROP, path[B_FULL]))
		elif what[1] == "chmod":
			from confFileBrowser import PermSetup
			self.session.openWithCallback(boundFunction(self.__permCallback,path), PermSetup, what[0], path)
		elif what[1] == "showfile":
			from ShowFileList import ShowFileList
			self.session.open(ShowFileList, path[B_FULL], selectlast=True)
		elif what[1] == "hideentry":
			if path[B_NAME] not in self.__hidelist:
				self.__newDMconf = True
				self.__hidelist.append(path[B_NAME])
			self.__fillListe()
		elif what[1] == "removeProtect":
			self.session.openWithCallback(boundFunction(self.__removeProtect,path), WidgetInput, PinCode=config.ParentalControl.folderpin.value)
		elif what[1] == "setProtect":
			if path[B_FULL] not in self.__permlist:
				self.__newDMconf = True
				self.__permlist.append(path[B_FULL])
			if config.ParentalControl.folderpin.value == PINCODEOFF:
				from Screens.ParentalControlSetup import ParentalControlChangePin
				self.session.openWithCallback(boundFunction(self.__PinCodeSet,path), ParentalControlChangePin, config.ParentalControl.folderpin, _("setup PIN"))
			else:
				self.lastpath = path[B_FULL]
				self.__fillListe()
		elif what[1] == "symlink":
			from confFileBrowser import SymlinkCreate
			self.session.openWithCallback(boundFunction(self.__symlinkCallback,path), SymlinkCreate, what[0], path[B_NAME], self.path)
		elif what[1] == "newdir":
			self.session.openWithCallback(self.__newdirCallback, WidgetInput, title=what[0], entryname=_("Name"), greenbutton=_("Create"))
		elif what[1] == "newfile":
			self.session.openWithCallback(self.__newfileCallback, WidgetInput, title=what[0], entryname=_("Name"), greenbutton=_("Create"))
		elif what[1] == "deleteMediaInfo":
			pathRemove(path[B_CFILE]+".png")
			pathRemove(path[B_CFILE]+".txt")
			self.__UpdateListEntry()
		elif what[1] == "createMediaInfo":
			if path[B_FILTER] & (FILTER_MOVIES | FILTER_ISO):
				searchstr = path[B_NAME]
				try:
					if path[B_FILTER] & FILTER_TS and path[B_DESC] != "":
						pos = path[B_DESC].find(" (")
						if pos>0:
							searchstr = path[B_DESC][0:pos]
						else:
							searchstr = path[B_DESC]
					else:
						pos = (len(path[B_NAME]) - len(path[B_EXT]) -1)
						searchstr =path[B_NAME][0:pos]
				except:
					pass
				self.session.openWithCallback(boundFunction(self.__movieSearchCallback,path), WidgetInput, title=what[0], entryname=_("search by"), greenbutton=_("Start"), default=searchstr)
			elif path[B_FILTER] & FILTER_SOUND:
				self.__startConsole(MI_SCANSOUND, path)
			elif path[B_FILTER] & FILTER_PICS:
				self.__startConsole(MI_SCANPICTURE, path)
		elif what[1] == "selectMediaPic":
			self.session.openWithCallback(boundFunction(self.__selectMI_Callback,path), gBrowser, setPath=path[B_FULL], filter=FILTER_JPEG)
		elif what[1] == "scanSubdirs":
			cmd = "%s '%s' '%s' %d %d ' ' &" %(GMEDIASCAN, path[B_FULL], DEFAULTGEMINICACHEDIR[:-1], 1, MI_SCANDIRRECURSIV)
			libgeminimain.sendDbus("gdaemon",0,cmd)
		elif what[1] == "createpackage":
			from confFileBrowser import PackSetup
			self.session.openWithCallback(boundFunction(self.__createpackageCallback, path), PackSetup, what[0], self.path)
		elif what[1] == "extractpackage":
			from confFileBrowser import ExtractSetup
			self.session.openWithCallback(boundFunction(self.__extractCallback, path), ExtractSetup, path, self.path)

#--------------------------------
	def __createpackageCallback(self, path, val=None, typ=None):
		if val is not None:
			#print val,typ, path
			kwargs={'func': C_MAKE_ARCHIVE, 'filelist': [path], 'package' : val + "/" + path[B_NAME], 'type' : typ, 'sourcedir' : self.path}
			BackGroundThread(kwargs)
			
	def __extractCallback(self, path, val=None):
		if val is not None:
			kwargs={'func': C_EXTRACT, 'filelist': [path], 'destdir' : val[0], 'password' : val[1]}
			BackGroundThread(kwargs)
		
	def __PinCode_Callback(self, val):
		if val:
			sel = self.getCurrentEntry()
			if sel and sel[3]:
				if sel[3][B_FILTER] & FILTER_DIR:
					self.lastpath = self.path
					self.path = sel[3][B_FULL]
					self.__fillListe()
				else:
					self.__startFile(sel[3][:])

	def __selectMI_Callback(self, path, file=None):
		if file is not None:
			self.__startConsole("selectMediaPic", path, file)

	def __movieSearchCallback(self, path, searchstr):
		if searchstr is not None:
			from searchMediaInfo import MovieList
			self.session.openWithCallback(self.__callbackMovieList, MovieList, searchstr, path)
			
	def __callbackMovieList(self, ret):
		if ret:
			self.__UpdateListEntry()

	def __newdirCallback(self, val):
		if val is not None:
			self.lastpath = self.path + "/" + val
			CreateDir(self.lastpath)
			self.__fillListe()
			
	def __newfileCallback(self, val):
		if val is not None:
			self.lastpath = self.path + "/" + val
			CreateFile(self.lastpath)
			self.__fillListe()

	def __symlinkCallback(self, path, val=None):
		if val is not None:
			if pathExists(val)==False:
				CreateSymlink(path[B_FULL],val)
				self.__fillListe()

	def __picplayCallback(self,ret=None):
		if ret:
			if ret != self.lastpath:
				index=0
				for x in self.GetList():
					if x[3][B_FULL]==ret:
						self.SetIndex(index)
						break
					index += 1

	def __setupCallback(self, newsetup, hidelist):
		if hidelist != self.__hidelist:
			self.__hidelist = hidelist
			self.__newDMconf = True
		if newsetup==True:
			self.__loadConfig()
		if newsetup==True or self.__newDMconf==True:
			self.__fillListe()

	def __favoritesCallback(self, val=None):
		geventNotifier.append((EVENT_BACKGROUND, self.__newBG_Event))
		if val is not None:
			self.lastpath = self.path
			self.path = val
			self.__fillListe()
		else:
			if self.filter == FILTER_NONE and cgevent.getConfig("Dmanager_startfirst",0):
				self.KeyExit()
			
	def __moviePlayerCallback(self,val=None):
		self.__fillListe()
		
	def __copy_move_Callback(self, func, last_path, val=None, destdir=None, jump=0):
		if val is not None and destdir is not None:
			function=C_COPY
			if func=="move":
				function=C_MOVE
			
			kwargs={'func': function, 'filelist': searchMovieExtension([last_path]), 'destdir' : destdir}
			if self.__ask:
				count_f=0
				count_d=0
				if last_path[B_FILTER] & FILTER_FILE:
					count_f += 1
				if last_path[B_FILTER] & FILTER_DIR:
					count_d += 1
				BackGroundThread(kwargs, self.session, count_f, count_d)
			else:
				BackGroundThread(kwargs)
			
			if jump:
				self.path = destdir
				self.lastpath = self.path + "/" + last_path[B_NAME]
				self.__fillListe()
			else:
				if func=="move":
					self.__fillListe()

	def __renameCallback(self, path, val=None):
		if val is not None and val != "":
			if path[B_NAME] != val:
				SetNewName(path, val)
				self.lastpath = self.path + val
				self.__fillListe()
			
	def __FolderPropCallback(self, path, val):
		if val is not None:
			libgeminimain.getPyList(SETFOLDERPROP, val)
			self.lastpath = path[B_FULL]
			self.__fillListe()
			
	def __permCallback(self, path, val=None):
		if val is not None:
			self.lastpath = path[B_FULL]
			SetPermission(val,path[B_FULL])
			self.__fillListe()
			
	def __removeProtect(self, path, val):
		if val and path[B_FULL] in self.__permlist:
			self.__newDMconf = True
			self.__permlist.remove(path[B_FULL])
			self.lastpath = path[B_FULL]
			self.__fillListe()
			
	def __PinCodeSet(self,path, val=True):
		self.lastpath = path[B_FULL]
		self.__fillListe()
#--------------------------------
	def __loadConfig(self):
		self.SortBy = cgevent.getConfig("Dmanager_SortBy", SORT_NAME)
		if self.SortBy < SORT_NAME or self.SortBy > SORT_SIZE_DOWN:
			self.SortBy = SORT_NAME
		self.__show_ts_help_files = cgevent.getConfig("Dmanager_show_ts_help_files",1)
		self.__show_system_files = cgevent.getConfig("Dmanager_show_hidden_files",0)
		self.__show_ts_info = cgevent.getConfig("Dmanager_show_ts_info",1)
		self.__ask = cgevent.getConfig("Dmanager_ask",1)
		self.__ok_is_green = cgevent.getConfig("Dmanager_ok_is_green",0)
		self.__media_scan = cgevent.getConfig("media_scan",1)
		self.__largeView = cgevent.getConfig("Dmanager_largeview",1)

	#def __setListHeigth(self,val):
	#	print val
	#	if val != self.isOrgHeight():
	#		if val==1:
	#			self.setOrgHeight()
	#		else:
	#			self.setSmallHeight()
	#	
	#	self.__largeString=""
	#	if self.isOrgHeight():
	#		self.__largeString="big"

	def __writeDMconf(self):
		if self.__newDMconf:
			self.__newDMconf = False
			try:
				wfile = open(DMCONFFILE, 'w')
				for x in self.__hidelist:
					wfile.write(x+"\n")
				wfile.write("::::\n")
				for x in self.__permlist:
					wfile.write(x+"\n")
				wfile.close()
			except Exception, e:
				print "[%s] <%s>"%(__name__,e)
#--------------------------------

	def __startConsole(self, func, path, search=" "):
		if self.__ConsoleRunning == False:
			cmd = None
			if func == MI_SCANPICTURE  or func == MI_SCANSOUND:
				cmd = "%s '%s' '%s' %d %d '%s'" %(GMEDIASCAN, path[B_FULL], path[B_CFILE], 1, func, search)
			elif func == MI_SCANDIR:
				cmd = "%s '%s' '%s' %d %d ' '" %(GMEDIASCAN, self.path, DEFAULTGEMINICACHEDIR[:-1], 1, func)
			elif func == "selectMediaPic":
				cmd = "%s '%s' '%s' %d %d ' '" %(GMEDIASCAN, search, path[B_CFILE], 0, MI_SCANPICTURE)
			if cmd:
				self.SetYB(_("Search running"))
				self.__ConsoleRunning = True
				self.Console.ePopen(cmd, boundFunction(self.__FinishedConsole,path))

	def __FinishedConsole(self, path, result, retval, extra_args = None):
		#print "__________________________FinishedConsole",path
		if self.__ConsoleRunning and path is not None:
			val = self.getCurrentEntry()
			if val and val[3] and val[3]==path:
				self.__UpdateListEntry()
		self.SetYB(_("Update"))
		self.__ConsoleRunning = False
#--------------------------------

	def KeyYellow(self):
		if self.__ConsoleRunning == False:
			val = self.getCurrentEntry()
			if val and val[3]:
				self.lastpath = val[3][B_FULL]
				self.__fillListe()
		
	def __UpdateListEntry(self):
		val = self.getCurrentEntry()
		if val and val[3]:
			if self.__largeString=="big":
				extratext = val[5]
				if val[3][B_FILTER] & (FILTER_SOUND | FILTER_MOVIES | FILTER_PICS):
					info = readCacheInfos(val[3][B_CFILE] + ".txt")
					extratext = createInfoString(info,val[3],False)
					
				if pathExists(val[3][B_CFILE] + ".png"):
					filePic = gLoadPixmap(val[3][B_CFILE] + ".png",cached=False)
				else:
					filePic = gLoadPixmap(self.__largeString + val[3][B_PICTURE])

				self.editEntry(self.GetIndex(), (val[0], filePic, val[2], val[3], ctoolsclass.getSeperatorPic(), extratext, None))
			else:
				if pathExists(val[3][B_CFILE] + ".png"):
					self.SetIcon(val[3][B_CFILE] + ".png")

			self.ShowHideInfoIcon(pathExists(val[3][B_CFILE] + ".txt"))
