#!/usr/bin/python
#-*- coding: iso-8859-1 -*-
import gtk
import pygtk, pygame, subprocess
import os,time,pynotify,sys,webbrowser


# Where is Application
# Copyright (C) 2009 Palumbo Roberto
# Author: Roberto Palumbo <palumborobertomail@gmail.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.


class Tabella(gtk.Window):
 def hide_window(self,widget,data=None):
	 self.hide_all()
	 return gtk.TRUE
	 
 def insert(self,nome,collocazione):
	 if (len(collocazione.strip())>0):
		self.listStore.append([nome,collocazione])

 def __init__(self):
	 global l_nome, l_collocazione, l_apps
	 gtk.Window.__init__(self)
	 self.vbox = gtk.VBox()
	 self.listStore = gtk.ListStore(str, str)
	 self.nome = gtk.TreeViewColumn(l_nome)
	 self.textRenderer = gtk.CellRendererText()
	 self.nome.pack_start(self.textRenderer, False)
	 self.nome.set_attributes(self.textRenderer, text = 0)
	 self.coll = gtk.TreeViewColumn(l_collocazione)
	 self.coll.pack_start(self.textRenderer, False)
	 self.coll.set_attributes(self.textRenderer, text = 1)
	 self.listBox = gtk.TreeView(self.listStore)
	 self.listBox.append_column(self.nome)
	 self.listBox.append_column(self.coll)
	 
	 self.vbox.pack_start(self.listBox)
	 self.set_title(l_apps)
	 self.set_position(gtk.WIN_POS_CENTER)
	 
	 self.add(self.vbox)
	 self.connect('destroy', self.hide_window) 
	 self.connect('delete_event',self.hide_window)
	 self.set_default_size(400,300)
	 


class Notifica:
	
	def mostra(self):
		self.nf.show()
	
	def tiponotifica(self,top,sub,image):
		if len(image)>0:
			self.nf = pynotify.Notification(top,sub,image)
		else:
			self.nf= pynotify.Notification(top,sub)
		self.nf.set_urgency(pynotify.URGENCY_CRITICAL)
		self.nf.set_timeout(6000)
		

class Tempo:
	time = 0
	def get_time(self):
		return self.time
	def __init__(self):
		self.time = 0
	def run(self):
		self.time +=1
		if self.time >50:
			self.time = 0
		time.sleep(0.1)

class SearchApp:


	def get_len_nome(self):
		return 'Nomi: '+str(len(self.nomi))+' Old: '+str(len(self.old))
	
	def __init__(self):
		self.nomi = []
		
		self.old = ""
		self.nomiold = []

	def cercafile(self,path):
		global updatemenu,advice_top,tab,advice_sub,advice_top_del,advice_sub_del,Categorie,trayball,n,softwarename,icontype,diricon
		submenu=""
		catname=""
		image = ""
		sel = ""
		x = 0

		for filename in os.listdir(path):
			if os.path.isfile(path+filename): 
				self.nomi.append(str(path+filename))

		selez = []

		if len(self.nomi)!=len(self.nomiold):
			x = 0
			if len(self.nomiold)>0:
				while x<len(self.nomi):
					nm = ''.join(self.nomiold)
					if nm.find(self.nomi[x])==-1:
						selez.append('I|'+self.nomi[x])
					x=x+1 
				x = 0
				while x<len(self.nomiold):
					nm = ''.join(self.nomi)
					if nm.find(self.nomiold[x])==-1:
						selez.append('E|'+self.nomiold[x])
					x=x+1 

		self.nomiold = []
		self.nomi = []
		
		for filename in os.listdir(path):
			if os.path.isfile(path+filename):
				self.nomiold.append(str(path+filename))
		n = Notifica()
		for sele in selez:
			frase = sele.split('|')
			sel = frase[1]
			if frase[0]=='I': 
				if pynotify.init('NEW INSTALLED APPLICATION'):
					f = open (sel,'r')
					catname = ""
					for l in f.readlines():
						s = l.split("=")
						
						for soft in softwarename:
							if s[0].upper()==soft.upper():
								advice_top=s[1]
						
						if s[0].upper()=='ICON':
							image = s[1]
							image = image.replace("\n","")
							
						if s[0].upper()=='CATEGORIES':
							submenu = s[1]
							for cat in Categorie:
								if submenu.find(cat[1])!=-1:
									catname = cat[0]
					f.close()
					fileimage = ""
					if image == "":
						fileimage = ""
					else:
						if image.find('.')==-1:
							for dr in diricon:
								for ic in icontype:
									if os.path.exists(dr+image+ic)==True: fileimage=dr+image+ic
						else:
							for dr in diricon:
								if os.path.exists(dr+image)==True: fileimage=dr+image
					n.tiponotifica(advice_top,advice_sub+catname,fileimage)
					n.mostra()
					tab.insert(advice_top.strip(),catname.strip())
					if (filewave!='None') and (len(filewave)>0):
						pygame.mixer.music.load(filewave)
						pygame.mixer.music.play()
			
					trayball.set_title(advice_top)
					trayball.set_message(advice_sub+catname)
					trayball.set_blinking(True)
					if (killall==1):
						updatemenu=1
			if frase[0]=='E':
				if pynotify.init('APP DELETED'):
					nomeapp = os.path.basename(frase[1])
					nomefile = nomeapp.split(".")
					n.tiponotifica(advice_top_del,advice_sub_del,'')
					n.mostra()
					trayball.set_title(advice_top_del)
					trayball.set_message(advice_sub_del)
					trayball.set_blinking(True)
			if updatemenu==1:
				process = subprocess.Popen('killall gnome-panel', shell=True, stdout=subprocess.PIPE)
				updatemenu=0
			return 1

class TrayBar:
	
	def set_message(self,text):
		self.message = text
	
	def set_title(self,text):
		self.title = text
		
	def set_ballon(self,title):
		self.ballon = text
	
	def show_hide(self,widget,response_id, data= None):
		trayball.set_blinking(False)
		if response_id == gtk.RESPONSE_OK:
			widget.hide()

	def set_blinking(self,text):
		if text == True:
			self.staticon.set_blinking(True)
		else:
			self.staticon.set_blinking(False)
		return self.staticon
		
	def quit(self,widget,data=None):
		if data:
			data.set_visible=False
		exit(0)

	def submenu(self,widget,button,time,data=None):
		if button == 3:
			if data:
				data.show_all()
				data.popup(None, None, None, 3, time)
		pass
		
	def about(self,widget,data=None):
		d = gtk.AboutDialog()
		d.set_name("Where is Application")
		d.set_version("1.5")
		f = open ('/usr/share/common-licenses/GPL-3','r')
		gpl = f.readlines()
		txt = ""
		for lin in gpl:
			txt+=lin
		f.close()
		d.set_license(txt)
		d.set_wrap_license(True)
		d.set_authors(["WIA @2009 Palumbo Roberto - palumborobertomail@gmail.com"])
		d.set_website("http://ubuntuwin.altervista.org")
		d.run()
		d.destroy()
		
	def activate(self,widget, data=None):
		global tab
		self.staticon.set_blinking(False)
		tab.show_all()
		
	def checkupdate(self,widget,data=None):
		webbrowser.open('http://ubuntuwin.altervista.org/index.php?id=19')
		
	def __init__(self):
		global l_aggiorna, intray
		self.staticon = gtk.StatusIcon()
		self.staticon.set_from_file('/usr/share/icons/wia.png')		
		
		self.menu = gtk.Menu()
		menuItem = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
		menuItem.connect('activate', self.about)
		self.menu.append(menuItem)
		menuItem = gtk.MenuItem(l_aggiorna)
		menuItem.connect('activate', self.checkupdate)
		self.menu.append(menuItem)
		menuItem = gtk.ImageMenuItem(gtk.STOCK_QUIT)
		menuItem.connect('activate', self.quit, self.staticon)
		self.menu.append(menuItem)
		
		self.message ="Wia"
		self.title="New Installed Application"
		self.ballon="Wia (Where is Application, @2009 Palumbo Roberto"
		self.staticon.set_tooltip(self.ballon) 
		self.staticon.set_blinking(False)
		self.staticon.connect("activate", self.activate)
		self.staticon.connect("popup_menu", self.submenu,self.menu)
		print str(intray)
		if int(intray)!=1:
			self.staticon.set_visible(False)
		else:
			self.staticon.set_visible(True)
		


class Main():
	def carica_dati(self):
		global home, filewave, killall
		# verifica l'esistenza di una configurazione
		if os.path.exists(home+'/wiaconfig.ini')==False:
			f = open(home+'/wiaconfig.ini','w')
			f.write('STARTUP=YES\n')
			f.write('TRAYBAR=YES\n')
			f.write('KILLALL=YES\n')
			f.close()
		
		f = open(home+'/wiaconfig.ini','r')
		g = f.readlines()
		f.close()
		for str in g:
			stringa = str.split('=')
			par = stringa[0].strip()
			val = stringa[1].strip()
			val = val.replace('\n','')
			if (par=='STARTUP') and (val=='YES'): 
				self.startup=1
			elif (par=='STARTUP') and (val=='NO'):
				self.startup=0
			if (par=='TRAYBAR') and (val=='YES'): 
				self.traybar=1
			elif (par=='TRAYBAR') and (val=='NO'):
				self.traybar=0
			if (par=='KILLALL') and (val=='YES'): 
				killall=1
			elif (par=='KILLALL') and (val=='NO'):
				killall=0
			if (par=='WAVE'):
				filewave=val
				
	def par(self,trad,nome):
		for tt in trad:
			stringa = tt.split('=')
			if stringa[0]==nome:
				return stringa[1]+' '
			
	def aprilingua (self,testo):
		global home,filewave,intray,tab,a,l_aggiorna,one, two,three, tm, trayball,stringa,advice_top,advice_top_del,advice_sub_del, advice_sub,stringa,Categorie,n,softwarename,icontype,diricon, l_apps, l_nome, l_collocazione
	
		f = open (testo,'r')
		
		trad = f.read().split('\n')
		
		f.close()
		
		print trad[0]
		
		l_apps=self.par(trad,'l_apps')
		l_nome=self.par(trad,'l_nome')
		l_collocazione=self.par(trad,'l_collocazione')
		advice_top = self.par(trad,'advice_top')
		advice_sub = self.par(trad,'advice_sub')
		advice_top_del = self.par(trad,'advice_top_del')
		advice_sub_del = self.par(trad,'advice_sub_del')
		l_aggiorna=self.par(trad,'l_aggiorna')
		softwarename = ['Name','Name['+self.par(trad,'softwarename')+']']
		Categorie = [self.par(trad,'Cat1'),'Utility'],[self.par(trad,'Cat2'),'Education'],[self.par(trad,'Cat3'),'Game'],[self.par(trad,'Cat4'),'Graphics'],[self.par(trad,'Cat5'),'Network'],[self.par(trad,'Cat6'),'Office'],[self.par(trad,'Cat7'),'Development'],[self.par(trad,'Cat8'),'AudioVideo'],[self.par(trad,'Cat9'),'Settings'],[self.par(trad,'Cat10'),'System'],[self.par(trad,'Cat11'),'System;Settings'],[self.par(trad,'Cat12'),'Other']

		
				
	def __init__(self):
		global updatemenu,home,filewave,intray,tab,a,l_aggiorna,one, two,three, tm, trayball,stringa,advice_top,advice_top_del,advice_sub_del, advice_sub,stringa,Categorie,n,softwarename,icontype,diricon, l_apps, l_nome, l_collocazione
		home = '/etc/'
		icontype =['.xpm','.png','.svg']
		diricon =['/usr/share/pixmaps/','/usr/share/icons/','/usr/share/icons/hicolor/scalable/apps/','/usr/share/icons/hicolor/48x48/apps/','/usr/share/icons/hicolor/22x22/apps/','/usr/share/icons/hicolor/32x32/apps/','/usr/share/icons/hicolor/16x16/apps/','/usr/share/app-install/icons/']
		path = '/etc/wia/'
		lingua = os.environ['LANG']
		updatemenu=0
		trovato = 'not found. English set as default language'
		
		for filename in os.listdir(path):
			if os.path.isfile(path+filename): 
				nomecompleto = str(filename)
				nome = nomecompleto.split(".")
				if (nome[0][0]==lingua[0]) and (nome[0][1]==lingua[1]):
					trovato = 'found'
					self.aprilingua(path+lingua[0]+lingua[1]+'.txt')
		
		if trovato!='found':
			self.aprilingua(path+'en.txt')
		
		
		#if stringa.find('it')!=-1:
			#l_apps='Applicazione installate recentemente'
			#l_nome='Nome'
			#l_collocazione='Collocazione nel menu\''
			#advice_top = 'Nuova applicazione installata'
			#advice_sub = 'Puoi trovare la nuova applicazione in '
			#advice_top_del = 'Applicazione rimossa'
			#advice_sub_del = 'Wia conferma la disinstallazione del software'
			#l_aggiorna='Cerca aggiornamenti'
			#softwarename = ['Name','Name[it]']
			#Categorie = ['Applicazioni-> Accessori','Utility'],['Applicazioni-> Istruzione','Education'],['Applicazioni-> Giochi','Game'],['Applicazioni-> Grafica','Graphics'],['Applicazioni-> Internet','Network'],['Applicazioni-> Ufficio','Office'],['Applicazioni-> Programmazione','Development'],['Applicazioni-> Audio e Video','AudioVideo'],[' Sistema -> Preferenze','Settings'],['Applicazioni-> Strumenti di Sistema','System'],[' Sistema -> Amministrazione','System;Settings'],['Applicazioni-> Altri','Other']
		#else:
			#l_apps='Recently installed apps'
			#l_nome='Name'
			#l_collocazione='Menu position'
			#advice_top = 'New Installed Application'
			#advice_sub = 'You can find the new installed application in '
			#advice_top_del = 'Apps deleted found'
			#advice_sub_del = 'Wia confirm that application was deleted.'
			#l_aggiorna='Check for updates'
			#softwarename = ['Name','Name[en]']
			#Categorie = [' Applications-> Accessories','Utility'],[' Applications-> Edutainment','Education'],[' Applications-> Games','Game'],[' Applications-> Graphics','Graphics'],[' Applications-> Internet','Network'],[' Applications-> Office','Office'],[' Applications-> Programming','Development'],[' Applications-> Sound&Video','AudioVideo'],[' System -> Settings','Settings'],[' Applications-> System Tools','System'],[' System -> Administration','System;Settings'],[' Applications-> Others','Other']
		# carica dati
		filewave = "None"
		pygame.init()
		self.traybar = 0
		self.carica_dati()
		intray = self.traybar
		#
		one = SearchApp()
		two = SearchApp()
		three = SearchApp()
		tm = Tempo()
		trayball = TrayBar()
		tab = Tabella()
		self.main_loop()
	
	def main_loop(self):
		global a, one, two, three, tm, trayball,n,tab,intray
		a = True
		while a == True:
			tm.run()
			if tm.get_time()==9:
				one.cercafile('/usr/share/applications/')
				if os.path.exists('/usr/share/applications/kde4')==True: 
					two.cercafile('/usr/share/applications/kde4/')
				if os.path.exists('/usr/share/applications/kde')==True: 
					three.cercafile('/usr/share/applications/kde/')
			while gtk.events_pending():
				gtk.main_iteration()

Main()

	
