#
# Morpheus Screensaver by gutemine
#
morpheus_version="5.6.9"
#
import os, random, struct
from enigma import quitMainloop, eBackgroundFileEraser
from Components.ActionMap import ActionMap, NumberActionMap
#import Components.ActionMap 
import GlobalActions 
from Components.config import config, ConfigInteger, ConfigBoolean, ConfigText, ConfigSubsection, getConfigListEntry, choicesList, ConfigSelection
from Components.MenuList import MenuList
from Components.ConfigList import ConfigListScreen
from enigma import ePoint, eTimer, getDesktop
from Components.Pixmap import Pixmap
from Plugins.Plugin import PluginDescriptor
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox 
from Components.Label import Label, MultiColorLabel
from Components.ServiceEventTracker import ServiceEventTracker        
from Components.Task import job_manager
from Screens.ChoiceBox import ChoiceBox 
from Screens.InfoBar import InfoBar
from Screens.InfoBarGenerics import *
import Screens.InfoBarGenerics
from enigma import eTimer, eServiceCenter, eDVBServicePMTHandler, iServiceInformation,  iPlayableService, eServiceReference, eEPGCache, eActionMap
from enigma import eDVBVolumecontrol     
from Components.SystemInfo import SystemInfo
import Screens.Standby 
from time import time, localtime, strftime     
import gettext
if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/WebInterface/WebChilds/Screenpage.py"):
	from Plugins.Extensions.WebInterface.WebChilds.Screenpage import ScreenPage
morpheus_dir="/usr/lib/enigma2/python/Plugins/Extensions/Morpheus"
global morpheus_ask
morpheus_ask=True
global morpheus_shown
morpheus_shown=0
global morpheus_movieshown
morpheus_movieshown=0
global morpheus_lastkey
morpheus_lastkey=time()
global morpheus_time
morpheus_time=0
global morpheus_standby
morpheus_standby=0
global morpheus_radio
morpheus_radio=0
global morpheus_media
morpheus_media=0
global morpheus_exit
morpheus_exit=False

# add local language file
sp=config.osd.language.value.split("_")
morpheus_language = sp[0]
if os.path.exists("%s/locale/%s" % (morpheus_dir,morpheus_language)):
        _=gettext.Catalog('morpheus', '%s/locale' % morpheus_dir).gettext

morpheus_colorlist= "black,white,red,green,blue,yellow"
morpheus_colors=[]
morpheus_colors=morpheus_colorlist.split(",")

config.plugins.Morpheus = ConfigSubsection()
config.plugins.Morpheus.stopped = ConfigInteger(default = 0, limits = (0, 240))
config.plugins.Morpheus.nokey = ConfigInteger(default = 0, limits = (0, 1440))
config.plugins.Morpheus.webifclick = ConfigBoolean(default = False)
if SystemInfo["DeepstandbySupport"]:
	config.plugins.Morpheus.nokeyaction = ConfigSelection(default = "Screensaver", choices = [ "Screensaver", "Standby", "Deepstandby", "Movie" ])
else:
	config.plugins.Morpheus.nokeyaction = ConfigSelection(default = "Screensaver", choices = [ "Screensaver", "Standby", "Shutdown", "Movie" ])
config.plugins.Morpheus.radio = ConfigInteger(default = 0, limits = (0, 240))
config.plugins.Morpheus.movie = ConfigText(default = "none")
config.plugins.Morpheus.media = ConfigInteger(default = 0, limits = (0, 240))
config.plugins.Morpheus.theme = ConfigText(default = "tux")
config.plugins.Morpheus.speed = ConfigInteger(default = 1, limits = (1, 60))
config.plugins.Morpheus.pixel = ConfigInteger(default = 5, limits = (1, 20))
config.plugins.Morpheus.background = ConfigSelection(default = "black", choices = [ "png" ]+morpheus_colors)
config.plugins.Morpheus.picture = ConfigText(default = "Reef")
config.plugins.Morpheus.fadepixel = ConfigInteger(default = 0, limits = (0, 80))
config.plugins.Morpheus.order = ConfigSelection(default = "forward", choices = [ "forward", "backward", "random", "randomlist" ])
config.plugins.Morpheus.fadespeed = ConfigInteger(default = 5, limits = (1, 60))
config.plugins.Morpheus.transparent = ConfigBoolean(default = False)
config.plugins.Morpheus.asktime = ConfigInteger(default = 10, limits = (0, 300))
config.plugins.Morpheus.deepstandby = ConfigInteger(default = 0, limits = (0, 240))

class Morpheus(Screen, ConfigListScreen):
	skin = """
		<screen position="center,center" size="580,480" title="Morpheus Screensaver Configuration" >
		<widget name="config" position="20,20" size="540,360" scrollbarMode="showOnDemand" />
		<widget name="buttonred" position="20,420" size="120,40" backgroundColor="red" valign="center" halign="center" zPosition="2"  foregroundColor="white" font="Regular;18"/>
		<widget name="buttongreen" position="160,420" size="120,40" backgroundColor="green" valign="center" halign="center" zPosition="2"  foregroundColor="white" font="Regular;18"/>
		<widget name="buttonyellow" position="300,420" size="120,40" backgroundColor="yellow" valign="center" halign="center" zPosition="2"  foregroundColor="white" font="Regular;18"/>
		<widget name="buttonblue" position="440,420" size="120,40" backgroundColor="blue" valign="center" halign="center" zPosition="2"  foregroundColor="white" font="Regular;18"/>
		<widget name="picturename" position="20,360" size="260,40" backgroundColor="white" valign="center" halign="center" zPosition="2"  foregroundColor="black" font="Regular;18"/>
		<widget name="themename" position="300,360" size="260,40" backgroundColor="white" valign="center" halign="center" zPosition="2"  foregroundColor="black" font="Regular;18"/>
	</screen>"""
	def __init__(self, session, args = 0):
		Screen.__init__(self, session)
		self.list = []
		self.list.append(getConfigListEntry(_("Start after paused TV for [1-240min] 0=disabled"), config.plugins.Morpheus.stopped))
		self.list.append(getConfigListEntry(_("Start after Radio for [1-240min] 0=disabled"), config.plugins.Morpheus.radio))
		self.list.append(getConfigListEntry(_("Start after Audio Mediaplay for [1-240min] 0=disabled"), config.plugins.Morpheus.media))
		self.list.append(getConfigListEntry(_("Start after no key for [1-1440min] 0=disabled"), config.plugins.Morpheus.nokey))
		if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/WebInterface/WebChilds/Screenpage.py"):
			self.list.append(getConfigListEntry(_("Webinterface click counts as key"), config.plugins.Morpheus.webifclick))
		self.list.append(getConfigListEntry(_("no key action"), config.plugins.Morpheus.nokeyaction))
# 		self.list.append(getConfigListEntry(_("Deepstandby after nokey for [1-240min] 0=disabled"), config.plugins.Morpheus.deepstandby))
		self.list.append(getConfigListEntry(_("Ask before starting for [1-300sec] 0=disabled"), config.plugins.Morpheus.asktime))
		self.list.append(getConfigListEntry(_("Change time [1-60sec]"), config.plugins.Morpheus.speed))
		self.list.append(getConfigListEntry(_("Change pixels [1-20]"), config.plugins.Morpheus.pixel))
		self.list.append(getConfigListEntry(_("Crossfade pixels [1-80] 0=disabled"), config.plugins.Morpheus.fadepixel))
		self.list.append(getConfigListEntry(_("Crossfade time [1-60sec]"), config.plugins.Morpheus.fadespeed))
		self.list.append(getConfigListEntry(_("Crossfade order"), config.plugins.Morpheus.order))
		self.list.append(getConfigListEntry(_("Background"), config.plugins.Morpheus.background))
#		self.list.append(getConfigListEntry(_("Transparency")"), config.plugins.Morpheus.transparent))
		self.onShown.append(self.setWindowTitle)
		ConfigListScreen.__init__(self, self.list)
		self.onChangedEntry = []
		self["buttonred"] = Label(_("Cancel"))
		self["buttongreen"] = Label(_("OK"))
		self["buttonyellow"] = Label(_("Skin"))
		self["buttonblue"] = Label(_("About"))
		if config.plugins.Morpheus.background.value == "png":                           
			self["picturename"] = Label(config.plugins.Morpheus.picture.value)
		else:
			self["picturename"] = Label(config.plugins.Morpheus.background.value)
		self["themename"] = Label(config.plugins.Morpheus.theme.value)
		self["setupActions"] = ActionMap([ "ColorActions", "SetupActions" ],
			{
			"green": self.save,
			"red": self.cancel,
			"yellow": self.theme,
			"blue": self.about,
			"save": self.save,
			"cancel": self.cancel,
			})

	def setWindowTitle(self):
		self.setTitle(_("Morpheus Screensaver Configuration"))

	def save(self):
		self.updateLabels()
		for x in self["config"].list:
			x[1].save()
		self.close(True)

	def cancel(self):
		for x in self["config"].list:
			x[1].cancel()
		self.close(False)

	def theme(self):
		global morpheus_exit
		morpheus_exit=False	
       		self.session.openWithCallback(self.askForTheme,ChoiceBox,_("Press OK to activate the selected skin."), self.getListThemes())

	def askForTheme(self,screensaver):                                        
		if screensaver is None:                                                
			self.session.open(MessageBox, _("No, do nothing."), MessageBox.TYPE_ERROR)
        	else:                                                                   
			config.plugins.Morpheus.theme.value = screensaver[1]
 			config.plugins.Morpheus.theme.save()
			if config.plugins.Morpheus.background.value == "png":                           
		 		self.session.openWithCallback(self.askForBackground,ChoiceBox,_("Press OK to activate the selected skin."), self.getListBackgrounds())
			else:
				self.session.open(ShowMorpheus)
				self.updateLabels()

	def askForBackground(self,background):                                        
		if background is None:                                                
			self.session.open(MessageBox, _("No, do nothing."), MessageBox.TYPE_ERROR)
        	else:                                                                   
			config.plugins.Morpheus.picture.value = background[1]
 			config.plugins.Morpheus.picture.save()
			self.session.open(ShowMorpheus)
			self.updateLabels()

        def updateLabels(self):
		if config.plugins.Morpheus.background.value == "png":                           
			self["picturename"].setText(config.plugins.Morpheus.picture.value)
		else:
			self["picturename"].setText(config.plugins.Morpheus.background.value)
		self["themename"].setText(config.plugins.Morpheus.theme.value)
		return
	#
	# I always wanted such a routine to check PNGs
	#
	def checkPNG(self,file, width, height,depth=8):
		if not os.path.exists(file):
	     		print "sorry, png file %s not found" % file
			return False
	    	p=open(file)
	    	header = p.read(8)
	    	if ( header != "\211PNG\r\n\032\n" ):
     			print "sorry, no png filei header"
			return False
    		try:
        		(length, type) = struct.unpack('>I4s', p.read(8))
    		except (OSError, IOError, struct.error):
        		print "sorry, png file unreadable"
        		return False

		if type == 'IEND':
			print "sorry, png file empty"
        		return False
    		elif type == 'IHDR':
        		data = p.read(length+4)
        		w, h, d = struct.unpack(">IIb", data[:9])
			print "checking png %s" % (file)
			print "has width: %i  checked for %i" % (w,width)
			print "png %s has height: %i checked for %i" % (file,h,height)
			print "png %s has depth: %i  checked for %i" % (file,d,depth)
			if w != width or h != height or d != depth:
				print "png is not OK"
				return False
			else:
				print "png is OK"
				return True

	def getListThemes(self):
        	screensaver = []
		if os.path.exists("%s/screensaver" % morpheus_dir):
			for file in os.listdir("%s/screensaver" % morpheus_dir):
				if file.endswith(".png"):
					file=file.replace(".png","")
					if self.checkPNG("%s/screensaver/%s.png" % (morpheus_dir,file),150,150,8):
		       	        		screensaver.append((file,file))
					else:
		       	        		screensaver.append(("! %s" % file,file))
		screensaver.sort()
        	screensaver2 = []
	       	screensaver2.append(("none","none"))
		screensaver2=screensaver2+screensaver
        	return screensaver2

	def getListBackgrounds(self):
		desktop = getDesktop(0)             
		w=int(desktop.size().width())
		h=int(desktop.size().height())
        	backgrounds = []
		if os.path.exists("%s/background" % morpheus_dir):
			for file in os.listdir("%s/background" % morpheus_dir):
				if file.endswith(".png"):
					file=file.replace(".png","")
					if self.checkPNG("%s/background/%s.png" % (morpheus_dir,file),w,h,8):
		       	        		backgrounds.append((file,file))
					else:
		       	        		backgrounds.append(("! %s" % file,file))
			for dir in os.listdir("%s/background" % morpheus_dir):
				if os.path.isdir("%s/background/%s" % (morpheus_dir,dir)) and os.path.exists("%s/background/%s" % (morpheus_dir,dir)):
					pngs_ok=True
					for file in os.listdir("%s/background/%s" % (morpheus_dir,dir)):
						if file.endswith(".png"):
							if not self.checkPNG("%s/background/%s/%s" % (morpheus_dir,dir,file),w,h,8):
								pngs_ok=False	
					if pngs_ok:
			       	        	backgrounds.append(("> %s" % dir, dir))
					else:
		       	        		backgrounds.append(("!> %s" % dir,dir))
		backgrounds.sort()
        	return backgrounds

	def about(self):
		self.session.open(MessageBox, _("Morpheus Screensaver Plugin\nby gutemine Version %s") % morpheus_version, MessageBox.TYPE_INFO)

def startConfig(session, **kwargs):
	session.open(Morpheus)

def autostart(reason, **kwargs):
	global morpheus_lastkey
	morpheus_lastkey=time()
	if kwargs.has_key("session") and reason == 0:
		session = kwargs["session"]
		print "[MORPHEUS] autostart checking"
		session.open(MorpheusCheck)

def main(menuid):
	if menuid != "system": 
		return [ ]
	return [(_("Screensaver"), startConfig, "morpheus", None)]

def mainmovie(session, service, **kwargs):
        session.nav.playService(service)
	global morpheus_session
	morpheus_session=session
	session.openWithCallback(askShowMovie, MessageBox, _("TV Screensaver?"), MessageBox.TYPE_YESNO, timeout=config.plugins.Morpheus.asktime.value)

def askShowMovie(answer):
	global morpheus_session
	global morpheus_time
	global morpheus_radio
	global morpheus_shown
	global morpheus_lastkey
	global morpheus_exit
	morpheus_exit=False
	if answer:
		service = morpheus_session.nav.getCurrentlyPlayingServiceReference()
	        serviceref=service.toString()
		part=[]
	        part=serviceref.split("/")
		moviefile=serviceref.replace(part[0],"")
		if moviefile.endswith(".ts"):
			config.plugins.Morpheus.movie.value=moviefile
			config.plugins.Morpheus.movie.save()
			morpheus_session.open(MessageBox, _("Screensaver")+": "+moviefile, MessageBox.TYPE_INFO)
		else:
			morpheus_session.open(MessageBox, _("No, do nothing."), MessageBox.TYPE_ERROR)
	else:
		morpheus_session.open(MessageBox, _("No, do nothing."), MessageBox.TYPE_ERROR)

def mainext(session,**kwargs): 
	if kwargs.has_key("session"):
		session = kwargs["session"]
	global morpheus_exit
	global morpheus_lastkey
	global morpheus_shown
	global morpheus_radio
	global morpheus_time
	morpheus_exit=False
	morpheus_lastkey=time()
	morpheus_shown=0
	morpheus_radio=0
	morpheus_time=0
        if config.plugins.Morpheus.nokeyaction.value != "Movie" or config.plugins.Morpheus.nokey.value == 0:
		session.open(ShowMorpheus)
	else:
		session.open(ShowMorpheusMovie)

def Plugins(**kwargs):
    	return [PluginDescriptor(where = [PluginDescriptor.WHERE_SESSIONSTART, PluginDescriptor.WHERE_AUTOSTART], fnc = autostart),
		PluginDescriptor(name=_("Screensaver"), description=_("never shown"), where=PluginDescriptor.WHERE_MENU, fnc=main),
            	PluginDescriptor(name=_("Screensaver"), where = PluginDescriptor.WHERE_EXTENSIONSMENU, fnc=mainext),
 	        PluginDescriptor(name=_("Screensaver"), description=_("Screensaver"), where = PluginDescriptor.WHERE_MOVIELIST, fnc=mainmovie)]

class MorpheusCheck(InfoBarTimeshift,InfoBarSeek,Screen):
    desktop = getDesktop(0)             
    w=int(desktop.size().width())
    h=int(desktop.size().height())
    skin = """
	<screen position="0,0" size="%i,%i" flags="wfNoBorder" zPosition="10">
	</screen>""" % (w,h)
    def __init__(self,session):
	self.session = session
        self.altshift = []
	Screen.__init__(self,session)
	self.skin = MorpheusCheck.skin
        print "[MORPHEUS] planning check"
	global morpheus_lastkey
	morpheus_lastkey=time()
	# thanks Dr. Best !
	eActionMap.getInstance().bindAction('', -0x7FFFFFFF, self.rcKeyPressed)

        self.TimerMorpheus = eTimer()
        self.TimerMorpheus.stop()
        self.TimerMorpheus.timeout.get().append(self.MorpheusChecking)
        self.TimerMorpheus.start(10000,True)
       	self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
      		{                                 
       		iPlayableService.evSeekableStatusChanged: self.EventSeekable,
#        		iPlayableService.evStart: self.EventStart,
#        		iPlayableService.evEnd: self.EventEnd,
 	       		iPlayableService.evEOF: self.EventEOF,
#  	      		iPlayableService.evSOF: self.EventSOF,
#        		iPlayableService.evCuesheetChanged: self.EventCue,
#        		iPlayableService.evBuffering: self.EventBuffer,
#        		iPlayableService.evStopped: self.EventStopped,
#        		iPlayableService.evUpdatedInfo: self.EventInfo,
      		})                                                      
#
#   thanks Dr. Best !
#
    def rcKeyPressed(self, key, flag):
	global morpheus_lastkey
	morpheus_lastkey=time()
	print "[MORPHEUS] key"
 	return 0

    def EventEOF(self):                                         
	print "[MORPHEUS] EOF"
	global morpheus_movieshown
	global morpheus_shown
	global morpheus_lastkey
        if morpheus_movieshown > 0:
		print "[MORPHEUS] replaying movie"
		# fake nokey  for EOF when Movie ends                         
      		morpheus_lastkey=time()-config.plugins.Morpheus.nokey.value*60
		#reset shown, and now that movie is stopped it does no harm to check again
		morpheus_shown=0
 		self.session.nav.stopService()                
	        self.TimerMorpheus.start(0,True)

#
# currently unneeded handlers
#
    def EventInfo(self):                                         
	print "[MORPHEUS] Info"
    def EventSOF(self):                                         
	print "[MORPHEUS] SOF"
    def EventCue(self):                                         
	print "[MORPHEUS] Cue"
    def EventBuffer(self):                                         
	print "[MORPHEUS] Buffer"
    def EventEnd(self):                                         
	print "[MORPHEUS] END"
    def EventStart(self):                                         
	print "[MORPHEUS] START"
    def EventStopped(self):                                         
	print "[MORPHEUS] STOPPED"
#
# here comes the show
#
    def EventSeekable(self):                                         
	global morpheus_time
	global morpheus_seekstate
	print "[MORPHEUS] SEEKABLE changed"
     	service = self.session.nav.getCurrentService()
	pauseable=service.pause()
	if pauseable:
	        print "[MORPHEUS] resets pause time"
		morpheus_time=0
	if self.isSeekable():   
		if morpheus_seekstate[0]:
			if morpheus_time==0:
			        print "[MORPHEUS] TV was stopped"
				morpheus_time=time()

    def MorpheusChecking(self):
        self.TimerMorpheus.stop()
	global morpheus_seekstate
	global morpheus_time
	global morpheus_shown
	global morpheus_movieshown
	global morpheus_radio
	global morpheus_media
	global morpheus_lastkey
	global morpheus_standby
	global morpheus_exit
	global morpheus_ask
	if (Screens.Standby.inStandby) and config.plugins.Morpheus.nokeyaction.value != "Deepstandby":
	 	print "[MORPHEUS] standby no checking ..."
		morpheus_lastkey=time()
		morpheus_shown=0
		morpheus_radio=0
		morpheus_media=0
		morpheus_time=0
		morpheus_exit=False
		self.TimerMorpheus.start(15000,True)
		return
	
#	print "[MORPHEUS] checking ..."
	if morpheus_shown > 0:
		shown=int(time()-morpheus_shown)
		print "[MORPHEUS] Screensaver shown since %i sec" % shown
		if config.plugins.Morpheus.nokeyaction.value == "Screensaver":
			self.TimerMorpheus.start(15000,True)
			return
 	serviceref = self.session.nav.getCurrentlyPlayingServiceReference()
	if serviceref is not None:
 		servicerefstr = serviceref.toString()
	else:
		servicerefstr=""
 	print "[MORPHEUS] serviceref %s" % servicerefstr
	if servicerefstr.startswith("1:0:2") is True:
		if morpheus_radio==0:
			print "[MORPHEUS] detected Radio"
			morpheus_radio=time()
		radio=int(time()-morpheus_radio)
		print "[MORPHEUS] Radio since: %d sec" % radio
	else:
		print "[MORPHEUS] no Radio"
		morpheus_radio=0
		radio=0
	if radio >= config.plugins.Morpheus.radio.value*60 and config.plugins.Morpheus.radio.value > 0 and morpheus_shown == 0:
		print "[MORPHEUS] wants to start because of Radio"
		morpheus_exit=False
		if config.plugins.Morpheus.asktime.value > 0:
			if morpheus_ask:
				morpheus_ask=False
				self.session.openWithCallback(self.AskShowMorpheus, MessageBox, _("TV Screensaver?"), MessageBox.TYPE_YESNO, timeout=config.plugins.Morpheus.asktime.value)
		else:
			self.AskShowMorpheus(True)
		self.TimerMorpheus.start(15000,True)
		return
	if servicerefstr.find("0:0:0:0:0:0:0:0:0:") is not -1 and not servicerefstr.startswith("4369:") and not servicerefstr.startswith("4097:") and not servicerefstr.startswith("4114:") and not servicerefstr.startswith("1:0:19:") and servicerefstr.startswith("1:0:") is False and not servicerefstr.endswith(".mpg") and not servicerefstr.endswith(".vob") and not servicerefstr.endswith(".avi") and not servicerefstr.endswith(".divx") and not servicerefstr.endswith(".mv4") and not servicerefstr.endswith(".mkv") and not servicerefstr.endswith(".mp4") and not servicerefstr.endswith(".ts"):
		if morpheus_media==0:
			print "[MORPHEUS] detected Audio Mediaplay"
			morpheus_media=time()
		media=int(time()-morpheus_media)
		print "[MORPHEUS] Audio Mediaplay since: %d sec" % media
	else:
		print "[MORPHEUS] no Audio Mediaplay"
		morpheus_media=0
		media=0
	if media >= config.plugins.Morpheus.media.value*60 and config.plugins.Morpheus.media.value > 0 and morpheus_shown == 0:
		print "[MORPHEUS] wants to start because of Mediaplay"
		morpheus_exit=False
		if config.plugins.Morpheus.asktime.value > 0:
			if morpheus_ask:
				morpheus_ask=False
				self.session.openWithCallback(self.AskShowMorpheus, MessageBox, _("TV Screensaver?"), MessageBox.TYPE_YESNO, timeout=config.plugins.Morpheus.asktime.value)
		else:
			self.AskShowMorpheus(True)
		self.TimerMorpheus.start(15000,True)
		return

	if self.isSeekable():   
		if morpheus_seekstate[0]:
			if morpheus_time==0:
			        print "[MORPHEUS] was paused"
				morpheus_time=time()
		else:
			        print "[MORPHEUS] was unpaused"
				morpheus_time=0
	if morpheus_time > 0:
		stopped=int(time()-morpheus_time)
		print "[MORPHEUS] paused since: %d sec" % stopped
	else:
		print "[MORPHEUS] not paused"
		morpheus_time=0
		stopped=0
	if stopped >= config.plugins.Morpheus.stopped.value*60 and config.plugins.Morpheus.stopped.value > 0 and morpheus_shown == 0:
		print "[MORPHEUS] wants to start because of stopped TV"
		morpheus_exit=False
		if config.plugins.Morpheus.asktime.value > 0:
			if morpheus_ask:
				morpheus_ask=False
				self.session.openWithCallback(self.AskShowMorpheus, MessageBox, _("TV Screensaver?"), MessageBox.TYPE_YESNO, timeout=config.plugins.Morpheus.asktime.value)
		else:
			self.AskShowMorpheus(True)
		self.TimerMorpheus.start(15000,True)
		return
	# 
	# check for lastkey
	#
	nokey=int(time()-morpheus_lastkey)
	# this should be not needed ....
	if nokey > 10000000:
		print "[MORPHEUS] greetings from the 70ties"
		morpheus_lastkey=time()
		nokey=0
	print "[MORPHEUS] nokey since %i sec" % nokey
	if nokey >= config.plugins.Morpheus.nokey.value*60 and config.plugins.Morpheus.nokey.value > 0:
		print "[MORPHEUS] wants to start because of nokey"
		morpheus_exit=False
		if config.plugins.Morpheus.asktime.value > 0:
			if config.plugins.Morpheus.nokeyaction.value == "Standby":
		       		if Screens.Standby.inStandby:
					print "[MORPHEUS] wants to Standby but already active"
				else:
					if morpheus_ask:
						morpheus_ask=False
						self.session.openWithCallback(self.AskDoStandby, MessageBox, _("TV Screensaver?"), MessageBox.TYPE_YESNO, timeout=config.plugins.Morpheus.asktime.value)
			elif config.plugins.Morpheus.nokeyaction.value == "Deepstandby":
				reason = ""
				recordings = self.session.nav.getRecordings()
				jobs = len(job_manager.getPendingJobs())
				next_rec_time = -1
				if not recordings:
					next_rec_time = self.session.nav.RecordTimer.getNextRecordingTime()	
				if recordings or (next_rec_time > 0 and (next_rec_time - time()) < 360):
					reason = _("Recording(s) are in progress or coming up in few seconds!") + '\n'
				if jobs:
					if jobs == 1:
						job = job_manager.getPendingJobs()[0]
						reason += "%s: %s (%d%%)\n" % (job.getStatustext(), job.name, int(100*job.progress/float(job.end)))
					else:
						reason += (_("%d jobs are running in the background!") % jobs) + '\n'
				if reason:
					print "[MORPHEUS] wants to Deepstandby but %s" % reason
				else:
					if morpheus_ask:
						morpheus_ask=False
						if SystemInfo["DeepstandbySupport"]:
							self.session.openWithCallback(self.AskDoDeepStandby, MessageBox, _("Deepstandby")+" "+_("TV Screensaver?"), MessageBox.TYPE_YESNO, timeout=config.plugins.Morpheus.asktime.value)
						else:
							self.session.openWithCallback(self.AskDoDeepStandby, MessageBox, _("Shutdown")+" "+_("TV Screensaver?"), MessageBox.TYPE_YESNO, timeout=config.plugins.Morpheus.asktime.value)
			elif config.plugins.Morpheus.nokeyaction.value == "Movie":
				if morpheus_movieshown == 0:
					if morpheus_ask:
						morpheus_ask=False
						self.session.openWithCallback(self.AskShowMovie, MessageBox, _("Movie")+" "+_("TV Screensaver?"), MessageBox.TYPE_YESNO, timeout=config.plugins.Morpheus.asktime.value)
				else:
					# just restart movie
					ref=eServiceReference(1, 0, "%s" % config.plugins.Morpheus.movie.value)
			        	self.session.nav.playService(ref)
	#				self.AskShowMovie(True)
			else: # Screensaver
				if morpheus_shown == 0:
					if morpheus_ask:
						morpheus_ask=False
						self.session.openWithCallback(self.AskShowMorpheus, MessageBox, _("TV Screensaver?"), MessageBox.TYPE_YESNO, timeout=config.plugins.Morpheus.asktime.value)
		else:
			if config.plugins.Morpheus.nokeyaction.value == "Standby":
		       		if Screens.Standby.inStandby:
					print "[MORPHEUS] wants to Standby but already active"
				else:
					if morpheus_ask:
						morpheus_ask=False
						self.AskDoStandby(True)
			elif config.plugins.Morpheus.nokeyaction.value == "Deepstandby":
				reason = ""
				recordings = self.session.nav.getRecordings()
				jobs = len(job_manager.getPendingJobs())
				next_rec_time = -1
				if not recordings:
					next_rec_time = self.session.nav.RecordTimer.getNextRecordingTime()	
				if recordings or (next_rec_time > 0 and (next_rec_time - time()) < 360):
					reason = _("Recording(s) are in progress or coming up in few seconds!") + '\n'
				if jobs:
					if jobs == 1:
						job = job_manager.getPendingJobs()[0]
						reason += "%s: %s (%d%%)\n" % (job.getStatustext(), job.name, int(100*job.progress/float(job.end)))
					else:
						reason += (_("%d jobs are running in the background!") % jobs) + '\n'
				if reason:
					print "[MORPHEUS] wants to Deepstandby but %s" % reason
				else:
					if morpheus_ask:
						morpheus_ask=False
						self.AskDoDeepStandby(True)
			elif config.plugins.Morpheus.nokeyaction.value == "Movie":
				if morpheus_ask:
					morpheus_ask=False
					self.AskShowMovie(True)
			else: # Screensaver
				if morpheus_shown == 0:
					if morpheus_ask:
						morpheus_ask=False
						self.AskShowMorpheus(True)
	self.TimerMorpheus.start(15000,True)

    def AskShowMorpheus(self,answer):
	global morpheus_time
	global morpheus_radio
	global morpheus_shown
	global morpheus_lastkey
	global morpheus_exit
	morpheus_exit=False
	global morpheus_ask
	morpheus_ask=True
	if answer:
		self.session.open(ShowMorpheus)
	else:
		morpheus_lastkey=time()
		morpheus_shown=0
		morpheus_radio=0
		morpheus_time=0

    def AskDoStandby(self,answer):
	global morpheus_time
	global morpheus_radio
	global morpheus_shown
	global morpheus_lastkey
	global morpheus_exit
	morpheus_exit=False
	global morpheus_ask
	morpheus_ask=True
	if answer:
		morpheus_exit=True
        	Notifications.AddNotification(Screens.Standby.Standby)
	else:
		morpheus_lastkey=time()
		morpheus_shown=0
		morpheus_radio=0
		morpheus_time=0

    def AskDoDeepStandby(self,answer):
	global morpheus_time
	global morpheus_radio
	global morpheus_shown
	global morpheus_lastkey
	global morpheus_exit
	morpheus_exit=False
	global morpheus_ask
	morpheus_ask=True
	if answer:
		print "[MORPHEUS] does Deepstandby now ..."
		morpheus_exit=True
         	Notifications.AddNotification(Screens.Standby.TryQuitMainloop, 1, config.plugins.Morpheus.asktime.value, False)
	else:
		morpheus_lastkey=time()
		morpheus_shown=0
		morpheus_radio=0
		morpheus_time=0

    def AskShowMovie(self,answer):
	global morpheus_time
	global morpheus_radio
	global morpheus_shown
	global morpheus_lastkey
	global morpheus_exit
	morpheus_exit=False
	global morpheus_ask
	morpheus_ask=True
	if answer:
		self.session.open(ShowMorpheusMovie)
	else:
		morpheus_lastkey=time()
		morpheus_shown=0
		morpheus_radio=0
		morpheus_time=0

class ShowMorpheus(Screen):
	desktop = getDesktop(0)             
	w=int(desktop.size().width())
	h=int(desktop.size().height())
	skin = """
		<screen position="0,0" size="%i,%i" flags="wfNoBorder" zPosition="8">
		<widget name="back" position="0,0" size="%i,%i" zPosition="8" font="Regular;26" valign="center" halign="center" backgroundColors="%s" foregroundColors="%s">
		</widget>
		<widget name="picture" position="0,0" size="%i,%i" zPosition="9">
		</widget>
		<widget name="pictureold" position="0,0" size="%i,%i" zPosition="9">
		</widget>
        	<widget name="screensaver" position="0,0" size="150,150" zPosition="10" transparent="1" alphatest="on" />	
		</screen>""" % (w,h,w,h,morpheus_colorlist,morpheus_colorlist,w,h,w,h)
	def __init__(self, session):
		Screen.__init__(self, session)
		self.skin = ShowMorpheus.skin
		self["back"] = MultiColorLabel()
		self["picture"] = Pixmap()
		self["pictureold"] = Pixmap()
		self["screensaver"] = Pixmap()
		self.picturenum=0
		self.picturecur=0
		global morpheus_shown
		global morpheus_radio
		global morpheus_time
		global morpheus_exit
		if (Screens.Standby.inStandby):
		        print "[MORPHEUS] screensaver not shown in standby"
			morpheus_lastkey=time()
			morpheus_shown=0
			morpheus_radio=0
			morpheus_time=0
			morpheus_exit=False
			return
			
	        self.TimerMorpheusScreensaver = eTimer()
      		self.TimerMorpheusScreensaver.stop()
   		self.TimerMorpheusScreensaver.timeout.get().append(self.movePosition)
                self.onLayoutFinish.append(self.byLayoutEnd)                    
               	self.onShow.append(self.movePosition)                           
		morpheus_shown=time()
	        print "[MORPHEUS] screensaver shown"
	 	serviceref = self.session.nav.getCurrentlyPlayingServiceReference()
		if serviceref is not None:
 			servicerefstr = serviceref.toString()
		else:
			servicerefstr=""
#		print "[MORPHEUS] serviceref %s" % servicerefstr
		if servicerefstr.startswith("1:0:2") is True:
			print "[MORPHEUS] no mute for Radio"
        	elif servicerefstr.find("0:0:0:0:0:0:0:0:0:") is not -1 and not servicerefstr.startswith("4369:") and not servicerefstr.startswith("4097:") and not servicerefstr.startswith("4114:") and not servicerefstr.startswith("1:0:19:") and servicerefstr.startswith("1:0:") is False and not servicerefstr.endswith(".mpg") and not servicerefstr.endswith(".vob") and not servicerefstr.endswith(".avi") and not servicerefstr.endswith(".divx") and not servicerefstr.endswith(".mv4") and not servicerefstr.endswith(".mkv") and not servicerefstr.endswith(".mp4") and not servicerefstr.endswith(".ts"):
			print "[MORPHEUS] no mute for Audio Mediaplay"
		else:
	                if (eDVBVolumecontrol.getInstance().isMuted()):
       	                	self.wasMuted = True                     
                        	print "mute already active"            
                	else:                                          
                        	self.wasMuted =  False                     
                        	eDVBVolumecontrol.getInstance().volumeToggleMute()

		self["setupActions"] = ActionMap([ "SetupActions" ],
			{
			"cancel": self.cancel,
			"ok": self.cancel,
			})

        def movePosition(self):                                                 
		desktop = getDesktop(0)             
		self.w=int(desktop.size().width())
		self.h=int(desktop.size().height())
		global morpheus_exit
		if morpheus_exit:	
			print "[MORPHEUS] was asked to exit"
			morpheus_exit=False
			self.cancel()
			
                if self.instance:                                               
			if config.plugins.Morpheus.theme.value != "none":
				x=random.randrange(0, desktop.size().width()-150, config.plugins.Morpheus.pixel.value)
				y=random.randrange(0, desktop.size().height()-150, config.plugins.Morpheus.pixel.value)
#				print "[MORPHEUS] moving to %i,%i" % (x,y)
                        	self["screensaver"].instance.move(ePoint(x,y))
			if self.picturenum > 0:
				if config.plugins.Morpheus.fadepixel.value > 0:
					self.fadenum=int(self.w/config.plugins.Morpheus.fadepixel.value)
#					print "[MORPHEUS] fadesteps: %i" % self.fadenum
					self.fadecur=0
					old=self.picturecur
					if config.plugins.Morpheus.order.value == "foreward" or config.plugins.Morpheus.order.value == "randomlist":
						new=self.picturecur+1
					elif config.plugins.Morpheus.order.value == "backward":
						new=self.picturecur-1
					else: # random
						new=random.randrange(0, self.picturenum-1,1)
					if new >= self.picturenum:
						new=0
					if new < 0:
						new=0
					self["pictureold"].instance.setPixmapFromFile("%s/background/%s/%s.png" % (morpheus_dir, config.plugins.Morpheus.picture.value,self.pictures[old]))
					self["picture"].instance.setPixmapFromFile("%s/background/%s/%s.png" % (morpheus_dir, config.plugins.Morpheus.picture.value,self.pictures[new]))
			       		self.FadeMorpheus = eTimer()
       					self.FadeMorpheus.stop()
        				self.FadeMorpheus.timeout.get().append(self.crossFade)
        				self.FadeMorpheus.start(int(config.plugins.Morpheus.fadespeed.value*1000/self.fadenum),True)
				else:
					print "[MORPHEUS] shows picture %i from %i" % (self.picturecur+1,self.picturenum)
					self["picture"].instance.setPixmapFromFile("%s/background/%s/%s.png" % (morpheus_dir, config.plugins.Morpheus.picture.value,self.pictures[self.picturecur]))
					if config.plugins.Morpheus.order.value == "foreward" or config.plugins.Morpheus.order.value == "randomlist" :
						self.picturecur=self.picturecur+1
					elif config.plugins.Morpheus.order.value == "backward":
						self.picturecur=self.picturecur-1
					else: # random
						self.picturecur=random.randrange(0, self.picturenum-1,1)
					if self.picturecur >= self.picturenum:
						self.picturecur=0
					if self.picturecur < 0:
						self.picturecur=0
	        			self.TimerMorpheusScreensaver.start(config.plugins.Morpheus.speed.value*1000,True)
			else:
        			self.TimerMorpheusScreensaver.start(config.plugins.Morpheus.speed.value*1000,True)

        def crossFade(self):                                                 
		global morpheus_exit
		if morpheus_exit:	
			print "[MORPHEUS] was asked to exit"
			morpheus_exit=False
			self.cancel()
		old=self.picturecur
		if config.plugins.Morpheus.order.value == "foreward" or config.plugins.Morpheus.order.value == "randomlist":
			new=self.picturecur+1
		elif config.plugins.Morpheus.order.value == "backward":
			new=self.picturecur-1
		else: # random
			new=random.randrange(0, self.picturenum-1,1)
		if new >= self.picturenum:
			new=0
		if new < 0:
			new=0
                self["pictureold"].instance.move(ePoint(-self.fadecur,0))
                self["picture"].instance.move(ePoint(self.w-self.fadecur,0))
		self.fadecur=self.fadecur+config.plugins.Morpheus.fadepixel.value
		if self.fadecur > self.w:
			self.fadecur=self.w
		if self.fadecur == self.w:
			# fade done, time for now picture
                	self["pictureold"].instance.move(ePoint(-self.fadecur,0))
                	self["picture"].instance.move(ePoint(self.w-self.fadecur,0))
			print "[MORPHEUS] fade done"
			if config.plugins.Morpheus.order.value == "foreward" or config.plugins.Morpheus.order.value == "randomlist":
				self.picturecur=self.picturecur+1
			elif config.plugins.Morpheus.order.value == "backward":
				self.picturecur=self.picturecur-1
			else: # random
				self.picturecur=random.randrange(0, self.picturenum-1,1)
			if self.picturecur >= self.picturenum:
				self.picturecur=0
			if self.picturecur < 0:
				self.picturecur=0
			print "[MORPHEUS] shows picture %i from %i" % (self.picturecur+1,self.picturenum)
 	        	self.TimerMorpheusScreensaver.start(config.plugins.Morpheus.speed.value*1000,True)
		else:
			# don't ask for more CPU power
			self.FadeMorpheus.start(int(config.plugins.Morpheus.fadespeed.value*1000/self.fadenum),True)
                                                                                
        def byLayoutEnd(self):                                                  
                if os.path.exists("%s/screensaver/%s.png" % (morpheus_dir,config.plugins.Morpheus.theme.value)):                            
 			print "[MORPHEUS] showing %s screensaver" % config.plugins.Morpheus.theme.value
	                self["screensaver"].instance.setPixmapFromFile("%s/screensaver/%s.png" % (morpheus_dir, config.plugins.Morpheus.theme.value))
                if config.plugins.Morpheus.background.value == "png":                            
	                if os.path.isdir("%s/background/%s" % (morpheus_dir,config.plugins.Morpheus.picture.value)): 
				self.pictures=[]
				# filling picturelist
				for file in os.listdir("%s/background/%s" % (morpheus_dir,config.plugins.Morpheus.picture.value)):
					if file.endswith(".png"):
						file=file.replace(".png","")
						self.pictures.append(file)
						self.picturenum=self.picturenum+1
		                if config.plugins.Morpheus.order.value == "randomlist":                            
					random.shuffle(self.pictures)
				print "[MORPHEUS] shows %i pictures from %s" % (self.picturenum, config.plugins.Morpheus.picture.value)
                	elif os.path.exists("%s/background/%s.png" % (morpheus_dir,config.plugins.Morpheus.picture.value)):                            
 				print "[MORPHEUS] shows %s picture" % config.plugins.Morpheus.picture.value
	                	self["picture"].instance.setPixmapFromFile("%s/background/%s.png" % (morpheus_dir, config.plugins.Morpheus.picture.value))
			else:
 				print "[MORPHEUS] picture %s not found" % config.plugins.Morpheus.picture.value
		else:
			c=0
			l=len(morpheus_colors)
			while config.plugins.Morpheus.background.value != morpheus_colors[c] and c < l:
				c=c+1
	       		self["back"].setForegroundColorNum(c)
	        	self["back"].setBackgroundColorNum(c)

	def cancel(self):
	        print "[MORPHEUS] screensaver closed"

		global morpheus_shown
		global morpheus_radio
		global morpheus_time
		global morpheus_lastkey
		global morpheus_exit

		morpheus_shown=0
		morpheus_radio=0
		morpheus_time=0
		morpheus_lastkey=time()
		morpheus_exit=True

      		self.TimerMorpheusScreensaver.stop()
		try:
			self.FadeMorpheus.stop()
		except:
			pass
	 	serviceref = self.session.nav.getCurrentlyPlayingServiceReference()
		if serviceref is not None:
 			servicerefstr = serviceref.toString()
		else:
			servicerefstr=""
#		print "[MORPHEUS] serviceref %s" % servicerefstr
		if servicerefstr.startswith("1:0:2") is True:
			print "[MORPHEUS] no unmute for Radio"
		elif servicerefstr.find("0:0:0:0:0:0:0:0:0:") is not -1 and servicerefstr.startswith("1:0:") is False and not servicerefstr.endswith(".mpg") and not servicerefstr.endswith(".vob") and not servicerefstr.endswith(".avi") and not servicerefstr.endswith(".divx") and not servicerefstr.endswith(".mv4") and not servicerefstr.endswith(".mkv") and not servicerefstr.endswith(".mp4") and not servicerefstr.endswith(".ts"):
			print "[MORPHEUS] no unmute for Mediaplay"
		else:
			try:
                		if not self.wasMuted:
                	        	eDVBVolumecontrol.getInstance().volumeToggleMute()
			except:
				pass
		self.close(True)

class ShowMorpheusMovie(InfoBar,InfoBarChannelSelection,Screen):
 	skin = """
 		<screen position="0,0" size="1280,720" flags="wfNoBorder" zPosition="9" transparent="1">
 		</screen>"""
	def __init__(self, session):
		Screen.__init__(self, session)
 		self.skin = ShowMorpheusMovie.skin
		global morpheus_shown
		global morpheus_movieshown
		global morpheus_radio
		global morpheus_time
		global morpheus_exit
		if (Screens.Standby.inStandby):
		        print "[MORPHEUS] screensaver not shown in standby"
			morpheus_lastkey=time()
			morpheus_shown=0
			morpheus_movieshown=0
			morpheus_radio=0
			morpheus_time=0
			morpheus_exit=False
			return
		self.oldservice = self.session.nav.getCurrentlyPlayingServiceReference()
	        if config.plugins.Morpheus.movie.value is None:
			morpheus_lastkey=time()
			morpheus_movieshown=0
			morpheus_shown=0
			morpheus_radio=0
			morpheus_time=0
			self.session.openwithCallback(self.cancel,MessageBox, _("No Screensaver movie defined"), MessageBox.TYPE_ERROR)
		else:
		        if os.path.exists(config.plugins.Morpheus.movie.value):
				morpheus_exit=True
#				self.session.nav.stopService()                
				morpheus_shown=time()
				morpheus_movieshown=time()
				# fake nokey  for EOF when Movie ends                         
                  		morpheus_lastkey=time()-config.plugins.Morpheus.nokey.value*60
				ref=eServiceReference(1, 0, "%s" % config.plugins.Morpheus.movie.value)
		        	self.session.nav.playService(ref)
			else:
				morpheus_lastkey=time()
				morpheus_movieshown=0
				morpheus_shown=0
				morpheus_radio=0
				morpheus_time=0
				moviefile=config.plugins.Morpheus.movie.value
				if config.plugins.Morpheus.asktime.value > 0:
					morpheus_timeout=config.plugins.Morpheus.asktime.value
				else:
					morpheus_timeout=10
				self.session.openWithCallback(self.cancel,MessageBox, _("Screensaver movie %s not found") % moviefile, MessageBox.TYPE_ERROR, timeout=morpheus_timeout)
			
		self["setupActions"] = ActionMap([ "SetupActions" ],
			{
			"cancel": self.cancel,
			"ok": self.cancel,
			})

	def cancel(self):
	        print "[MORPHEUS] movie screensaver closed"

		global morpheus_shown
		global morpheus_movieshown
		global morpheus_radio
		global morpheus_time
		global morpheus_lastkey
		global morpheus_exit

		morpheus_shown=0
		morpheus_movieshown=0
		morpheus_radio=0
		morpheus_time=0
		morpheus_lastkey=time()
		morpheus_exit=True
		self.session.nav.stopService()                
	        self.session.nav.playService(self.oldservice)
		self.close(True)
#
# let's hack the seekstat
#
def setSeekState(self, state):
	service = self.session.nav.getCurrentService()

	if service is None:
		return False

	if not self.isSeekable():
		if state not in (self.SEEK_STATE_PLAY, self.SEEK_STATE_PAUSE):
			state = self.SEEK_STATE_PLAY

	pauseable = service.pause()

	if pauseable is None:
		print "not pauseable."
		state = self.SEEK_STATE_PLAY

	self.seekstate = state

	if pauseable is not None:
		if self.seekstate[0]:
			print "resolved to PAUSE"
			pauseable.pause()
		elif self.seekstate[1]:
			print "resolved to FAST FORWARD"
			pauseable.setFastForward(self.seekstate[1])
		elif self.seekstate[2]:
			print "resolved to SLOW MOTION"
			pauseable.setSlowMotion(self.seekstate[2])
		else:
			print "resolved to PLAY"
			pauseable.unpause()

	for c in self.onPlayStateChanged:
		c(self.seekstate)
	#
	# I'm to lazy to do it the clean way :-)
	#
	global morpheus_seekstate
	morpheus_seekstate=self.seekstate

	self.checkSkipShowHideLock()

	return True

InfoBarSeek.setSeekState=setSeekState

if os.path.exists("/usr/lib/enigma2/python/Plugins/Extensions/WebInterface/WebChilds/Screenpage.py"):
	webif_render=ScreenPage.render

	def morpheus_render(self, request):
		if config.plugins.Morpheus.webifclick.value is True:                           
			print "[MORPHEUS] click"
			global morpheus_lastkey
			morpheus_lastkey=time()
		return webif_render(self, request)

	ScreenPage.render=morpheus_render

