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


# WIA (Where Installed App?) - @2009 Palumbo Roberto
# Email: palumborobertomail@gmail.com
# Web: http://ubuntuwin.blogspot.com
# This a GPL python utility check periodically for new installed apps.
# If there is a new app installed this utility show you a notification
# who show you the menu name of the installed apps
# Don't change these infos to keep the license


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 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())
					trayball.set_title(advice_top)
					trayball.set_message(advice_sub+catname)
					trayball.set_blinking(True)
			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)
					 
		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):
		dialog = gtk.MessageDialog(
		parent         = None,
		flags          = gtk.DIALOG_DESTROY_WITH_PARENT,
		type           = gtk.MESSAGE_INFO,
		buttons        = gtk.BUTTONS_OK,
		message_format = "@2009 Palumbo Roberto <palumborobertomail@gmail.com>\n \n Website: http://ubuntuwin.blogspot.com")
		dialog.set_title('About')
		dialog.connect('response', self.show_hide)
		dialog.show() 
		
	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.blogspot.com/search/label/wia')
		
	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_from_stock(gtk.STOCK_ABOUT)
		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
		# 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.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
					
	def __init__(self):
		global home,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
		stringa = os.environ['LANG']
		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/']
		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
		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()==5:
				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()

	
