#!/usr/bin/python
"""Copyright (C) 2009  Kristof Bamps

    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, either version 2 of the License, or
    (at your option) any later version.

    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, see <http://www.gnu.org/licenses/>.
"""

import GoogleReader
import urllib, urllib2
import webbrowser
from threading import Thread
import gtk.glade
import egg.trayicon
import time
import pygtk
pygtk.require("2.0")
import gobject
import os
import pynotify
import dbus
import dbus.service
import dbus.mainloop.glib
import ConfigParser


VERSION = '1.1.2'

#########
#Main class: the tray icon
#	
class grnotify(Thread):
    
    #--------------------------------------------
    # initialization
    #--------------------------------------------
    
    #configuration options if there is no config file
    def initialConfig(self):
        if not (os.path.exists(os.path.join(os.environ['HOME'], '.grnotify/'))):
            os.mkdir(os.path.join(os.environ['HOME'], '.grnotify/'))
	    self.newUser = True
        self.user = ''
	self.newUser = False
	self.broken = False
        self.passwd = ''
        self.waitTime = 300
        self.numberFeeds = 10
        self.numberTitles = 50
        self.showCounter = True
        self.showNotification = True
        self.iconNew = '/usr/share/pixmaps/grnotify/new.gif'
        self.iconNoNew = '/usr/share/pixmaps/grnotify/nonew.gif'
        self.iconBroken = '/usr/share/pixmaps/grnotify/broken.gif'
        self.openReader = True
        self.autoHide = False
        self.useKeyRing = True
	self.ok = False
                
                
    def saveConfig(self):
        CONFIGFILE = os.path.join(os.environ['HOME'], '.grnotify/config')
        config = ConfigParser.ConfigParser()
        config.add_section("User settings")
        config.set("User settings", "username", self.user)
        if not self.useKeyRing or not self.saveKeyRing(self.passwd):
            config.set("User settings", "password", self.passwd)
        config.set("User settings", "wait time", self.waitTime)
        config.set("User settings", "maximum number of feeds", self.numberFeeds)
        config.set("User settings", "maximum number of titles", self.numberTitles)
        config.set("User settings", "show counter", self.showCounter)
        config.set("User settings", "show notification", self.showNotification)
        config.set("User settings", "open reader", self.openReader)
        config.set("User settings", "autohide", self.autoHide)
        config.set("User settings", "useKeyRing", self.useKeyRing)

        config.add_section("Icons")
        config.set("Icons", "New items icon", self.iconNew)
        config.set("Icons", "No new items icon", self.iconNoNew)
        config.set("Icons", "Broken icon", self.iconBroken)
        
        config.write(open(CONFIGFILE, 'w'))

    def readConfig(self):
        CONFIGFILE = os.path.join(os.environ['HOME'], '.grnotify/config')
        if os.path.isfile(CONFIGFILE):
	    try:
		config = ConfigParser.ConfigParser()
		config.read(CONFIGFILE)
		if config.has_option("User settings", "password"):
		    self.passwd = config.get("User settings", "password")
		else:
		    self.passwd = self.readKeyRing()
		self.user = config.get("User settings", "username")
		self.waitTime = int(config.get("User settings", "wait time"))
		self.numberFeeds = int(config.get("User settings", "maximum number of feeds"))
		self.numberTitles = int(config.get("User settings", "maximum number of titles"))
		self.showCounter = config.get("User settings", "show counter").lower() != "false"
		self.showNotification = config.get("User settings", "show notification").lower() != "false"
		self.openReader = config.get("User settings", "open reader").lower() != "false"
		self.autoHide = config.get("User settings", "autohide").lower() != "false"
		self.useKeyRing = config.get("User settings", "useKeyRing").lower() != "false"
		
		self.iconNew = config.get("Icons", "New items icon")
		self.iconNoNew = config.get("Icons", "No new items icon")
		self.iconBroken = config.get("Icons", "Broken icon")
	    except:
		self.initialConfig()
		self.broken = True
		os.remove(CONFIGFILE)
	else:
	    self.newUser = True
            
    def saveKeyRing(self, passwd):
        keyring = "login"
        try:
            
            import gnomekeyring
            import gconf
            gnomekeyring.create_sync(keyring, None)
        except gnomekeyring.AlreadyExistsError:
            pass
        
        try:
            auth_token = gnomekeyring.item_create_sync(
                keyring,
                gnomekeyring.ITEM_GENERIC_SECRET,
                "grnotify user password",
                dict(appname="grnotify"),
                passwd, True)
            gconf.client_get_default().set_int("/apps/grnotify/keyring_auth_token", auth_token)
            return 1
        except:
            return 0

    def readKeyRing(self):
        keyring = "login"
        password = ''
        try:
            
            import gnomekeyring
            import gconf
            gnomekeyring.create_sync(keyring, None)  
        except gnomekeyring.AlreadyExistsError:  
            pass 
        auth_token = gconf.client_get_default().get_int("/apps/grnotify/keyring_auth_token")
        if auth_token > 0:
            try:
                password = gnomekeyring.item_get_info_sync(keyring, 
                            auth_token).get_secret()
            except:
                pass
        return password

    def openGoogleReader(self, widget = None):
        url = "https://www.google.com/accounts/ServiceLoginAuth?" + \
          urllib.urlencode({'Email':grnotify_app.greader.email}) + "&" + \
          urllib.urlencode({'Passwd':grnotify_app.greader.passwd}) + \
          "&service=reader&continue=" + \
          "https://www.google.com/reader&nui=1" 
        webbrowser.open_new_tab(url)

    def __init__(self):
        Thread.__init__(self)
        self.initialConfig()
        self.readConfig()
        self.feeds = []
        self.titles = []
        self.unread = 0
        self.greader = GoogleReader.GoogleReader()
        self.greader.login(self.user, self.passwd)
        # create a trayicon object
        self.tray_icon = egg.trayicon.TrayIcon("grnotify")

        # create a eventbox object which is going to be added to the trayicon object
        self.grnotify_eventbox = gtk.EventBox()  

        # add the eventbox object to the trayicon object for event handling (click, scroll)
        self.tray_icon.add(self.grnotify_eventbox)
        
        # connect "click" event to their handlers
        self.grnotify_eventbox.connect("button_press_event", self.clicked)
        
        
        # create container
        self.traycontainer = gtk.HBox()
        
        # create the image object
        self.icon = gtk.Image()
        # and the unread label
        self.unread_label = gtk.Label('? ')
        
        # set the image pixmap
        self.icon.set_from_file(self.iconBroken)
        # add the image object to the tray container
        self.traycontainer.pack_start(self.icon, False, False, padding = 0)
        self.traycontainer.pack_start(self.unread_label, False, False, padding = 0)
        self.grnotify_eventbox.add(self.traycontainer)
        
        
        # create the tooltip, pass it the actual information and add it to the grnotify_eventbox
        self.tooltip = gtk.Tooltips()
        self.tooltip_message = "Getting feed info"
        self.tooltip.set_tip(self.grnotify_eventbox,self.tooltip_message)
        self.tooltip.enable()
        
        # show the trayicon (+ etc.)
        self.tray_icon.show_all() 
        # self.properties = properties_dialog()
        self.menu = tray_menu(self)
        self.about = about_dialog()

    #
    #---- clicked  :the eventbox (from the trayicon) click event handler
    #       
    def clicked(self,widget,event):
        # right click
        if event.button == 3:
            self.menu = tray_menu(self)
        # open the tray_menu (includes quit and about)
            self.menu.popup(event)
        if event.button == 1:
            if self.ok and self.openReader:
                self.openGoogleReader()
            else:	
                self.getUnreadFeeds()
                
    def run(self):
	if self.newUser:
		configure_window()
	while not self.ok:
		self.refresh()
		time.sleep(30)
        while (1):  
            time.sleep(self.waitTime)
            self.refresh()
    
    def refresh(self, forced = False):
	    if self.broken:		
		self.notification('Please fill in your info in preferences')
		self.broken = False
            self.refresher = updater(forced)
            self.refresher.start()
            
    def updateToolTip(self):
        gtk.gdk.threads_enter()
	if self.ok:
	    message = str(self.greader.totalUnread) + ' unread item'
	    if self.greader.totalUnread != 1: 
		message += 's'
	    i = 0
	    for feed in self.feeds:
		if i < self.numberFeeds:
		    message += '\n' + feed.title + ' : ' + str(feed.unreadItems)
		i+= 1
	else:
	    message = 'Something went wrong.\nPlease check your internet connection and settings.'
        self.tooltip.set_tip(self.grnotify_eventbox, message)
        gtk.gdk.threads_leave()
        
    def updateIcon(self):
        gtk.gdk.threads_enter()
        if not self.ok:
            grnotify_app.icon.set_from_file(self.iconBroken)
            grnotify_app.unread_label.set_text('? ')
        elif self.greader.totalUnread == 0:
            grnotify_app.icon.set_from_file(self.iconNoNew)
            grnotify_app.unread_label.set_text(str(self.greader.totalUnread)+ ' ')
        else:
            grnotify_app.icon.set_from_file(self.iconNew)
            grnotify_app.unread_label.set_text(str(self.greader.totalUnread)+ ' ')
        grnotify_app.icon.show_all()
        grnotify_app.unread_label.show_all()
        
        if not self.showCounter or self.greader.totalUnread == 0:
            grnotify_app.unread_label.hide()
        if self.autoHide and self.greader.totalUnread == 0:
            grnotify_app.icon.hide()
        gtk.gdk.threads_leave()
        
    #shows the notification
    def notify(self, current, previous):
        try:
            if current > 0:
                if current - previous == 1:
                    self.notification("You have 1 new unread item")
                elif current > previous:
                    self.notification("You have " + str(current-previous) + " new unread items")
        except:
            pass
        
    def notification(self, message):
        if self.showNotification:
            #try:
                if pynotify.init("GrNotify Notification Bubble"):
                    bubble = pynotify.Notification("GrNotify", message, None, grnotify_app.grnotify_eventbox)
                    bubble.set_urgency(pynotify.URGENCY_NORMAL)
                    bubble.set_timeout(5000)
                    bubble.show()
            #except:
             #   pass
                
######################### BEGIN CLASS TRAY MENU ##########################
#Create the configure window
#Written by Kristof Bamps @ Feb 5 2008
#
class tray_menu:
    def __init__(self, parent):
    # create the window object - instance of gtk.Menu
        self.parent = parent
        self.window = gtk.Menu()
        self.menubar = gtk.MenuBar()

    # create the menu separator menu item object
        menu_item_refresh = gtk.ImageMenuItem('gtk-refresh',None)
        menu_item_refresh.connect('activate',self.refresh_clicked)
        
        menu_google_reader = gtk.ImageMenuItem ('Open Google Reader', None)
        menu_google_reader.connect ('activate', self.openGoogleReader)
        
        menu_mark_read = gtk.ImageMenuItem ('Mark all as read', None)
        menu_mark_read.connect('activate', self.markAllRead)
        if (self.parent.greader.totalUnread == 0 ):
            menu_mark_read.set_sensitive (0)

        menu_item_feed = gtk.ImageMenuItem ('Subscribe to feed', None)
        menu_item_feed.connect('activate',self.feed_clicked)

        # create the about menu item object with it's icon
        menu_item_about = gtk.ImageMenuItem('gtk-about',None)

        # connect a handler to it
        menu_item_about.connect('activate',self.about_clicked)
        menu_item_preferences = gtk.ImageMenuItem('gtk-preferences',None)
        menu_item_preferences.connect('activate',self.preferences_clicked)

        # add the preferences menu item
        if self.parent.openReader:
            self.window.add(menu_item_refresh)
            self.window.add(menu_google_reader)
        else:
            self.window.add(menu_google_reader)
            self.window.add(menu_item_refresh)
        self.window.add(menu_mark_read)
        self.window.add(menu_item_feed)
        self.window.add(menu_item_preferences)
        self.window.add (gtk.SeparatorMenuItem())
        
        view_item = gtk.Menu()
        menu_view_item = gtk.MenuItem ('View Items', None)		
        menu_view_item.set_submenu (view_item)
        self.setTitels(view_item)
        if (self.parent.greader.totalUnread == 0 or self.parent.numberTitles == 0):
            menu_view_item.set_sensitive (0)
        self.window.add (menu_view_item)
        
        self.window.add (gtk.SeparatorMenuItem())
    # add the about menu item to the menu object
        self.window.add(menu_item_about)
        
    # create the quit menu item object with it's icon
        menu_item_quit = gtk.ImageMenuItem('gtk-quit',None)

    # connect a handler to it
        menu_item_quit.connect('activate',self.exit)

    # add the quit menu item to the menu object    
        self.window.add(menu_item_quit)
        
    # show the menu
        self.window.show_all() 
    def exit(self,widget):
    # quit menu item handler -> quit the application 
        os.system("kill " + str (os.getpid()))
        
    def feed_clicked (self, widget):
        popup = feedPopup()
        
    def markAllRead (self, widget):
        self.parent.greader.markAllRead()
        self.parent.refresh()
        
    def refresh_clicked (self, widget):
        self.parent.refresh()
    
    def preferences_clicked (self, widget):
        configureWindow = configure_window()
    
    def about_clicked(self,widget):
    # about menu item handler -> create the about window
        grnotify_app.about.create()
        
    def popup(self,event):
    # popup-show the menu
        self.window.popup( None, None, None, 0, event.time); 
    
    def close(self,widget):
        # the warning close button has been clicked (or the window was closed else way)
        grnotify_app.warning_close_button = True
        
        # the window isn't opened
        grnotify_app.warning_window_opened = False
        self.window.destroy()
        
    def openGoogleReader(self, widget = None):
        url = "https://www.google.com/accounts/ServiceLoginAuth?" + \
          urllib.urlencode({'Email':grnotify_app.greader.email}) + "&" + \
          urllib.urlencode({'Passwd':grnotify_app.greader.passwd}) + \
          "&service=reader&continue=" + \
          "https://www.google.com/reader&nui=1" 
        webbrowser.open_new_tab(url)
        
    def openlink(self, item):
        i = 0
        for item2 in self.items:
            if item2 == item:
                webbrowser.open_new_tab(self.titles[i].link )
                self.markRead(self.titles[i].id, self.titles[i].feed)
                self.parent.refresh(forced=True)
            i = i+1
            
    def markRead(self, id, feed):
        req = urllib2.Request ('http://www.google.com/reader/api/0/token')
        f = urllib2.urlopen (req)
        token = f.read()
        
        data = { 'i' : id, 's' : feed, 'T' : token, 'ac' : 'edit-tags' , 'a' : 'user/-/state/com.google/read' }
        data = urllib.urlencode (data)
        url = 'http://www.google.com/reader/api/0/edit-tag'
        req = urllib2.Request (url, data)
        f = urllib2.urlopen (req)
        
    def setTitels(self, menu) :
            self.items = []
            self.titles = []
            if self.parent.numberTitles != 0:
                if (self.parent.unread <= 10 or self.parent.numberTitles <= 10) and self.parent.unread >= 1:
                    for title in self.parent.titles:
                        self.titles.append(title)
                        self.items.append(gtk.MenuItem (title.title, None))
                        self.items[-1].connect ('activate', self.openlink)
                        menu.add (self.items[-1])
                        
                else:
                    self.menus = []
                    self.feedMenus = []
                    for feed in self.parent.feeds:
                        self.menus.append( gtk.MenuItem (feed.title, None))
                        self.feedMenus.append( gtk.Menu())
                        self.menus[-1].set_submenu (self.feedMenus[-1])
                        added = False
                        for title in self.parent.titles:
                            if title.feed == feed.id:
                                added = True
                                self.titles.append(title)
                                self.items.append (gtk.MenuItem (title.title, None))
                                self.items[-1].connect ('activate', self.openlink)
                                self.feedMenus[-1].add(self.items[-1])
                        if added:
                            menu.add(self.menus[-1])
                        else:
                            del self.menus[-1]
            
class about_dialog:
    def create(self):
        CONFIG = '/usr/share/grnotify/'
        # set the glade file
        self.gladefile = CONFIG + "about.glade"  

        # create the widget three  
        self.wTree = gtk.glade.XML(self.gladefile, "window_about")
        self.wTree.signal_autoconnect(self)

        # create the "about" window
        self.window = self.wTree.get_widget("window_about")
        self.window.set_copyright("Version " + VERSION)
        self.window.set_name("GrNotify")
        #self.window.set_website("http://grnotify.sf.net")
        self.window.set_website_label("http://grnotify.sf.net")
        self.window.set_comments("GrNotify is a simple Python written\ntray application that will allow you\nto know when there are new items\nin the Google Reader.")
        self.window.connect("response", lambda d, r: self.close())

    def close(self):
        self.window.destroy()

    def on_close_button_clicked(self, button=None, data=None):
    #Close the dialog
        self.window.destroy()
        
class updater (Thread):
    def __init__(self, forced = False):
        Thread.__init__(self)
        self.forced = forced
    def run(self):
        try:
	    if self.forced or not grnotify_app.ok or grnotify_app.broken:
		    grnotify_app.greader.login(grnotify_app.user, grnotify_app.passwd)
	    grnotify_app.feeds = grnotify_app.greader.getUnreadFeeds()
	    grnotify_app.ok = True
	    
	    
	    grnotify_app.updateToolTip()
	    grnotify_app.updateIcon()
	    if grnotify_app.unread != grnotify_app.greader.totalUnread or self.forced:
		grnotify_app.notify(grnotify_app.greader.totalUnread, grnotify_app.unread)
		grnotify_app.unread = grnotify_app.greader.totalUnread
		grnotify_app.titles = grnotify_app.greader.getUnreadTitles(grnotify_app.numberTitles)
	except:
            grnotify_app.ok = False
	    grnotify_app.updateToolTip()
	    grnotify_app.updateIcon()
            pass
            
            
class feedPopup:
    def __init__(self):
        CONFIG = '/usr/share/grnotify/'

    #Create the dialog
        self.gladefile = CONFIG + "feed.glade"
        self.xml = gtk.glade.XML(self.gladefile)  
        self.xml.signal_autoconnect(self)
        self.window = self.xml.get_widget('main_window')
        self.window.set_title('GrNotify: Add feed')
    def on_close_button_clicked(self, button=None, data=None):
    #Close the dialog
        self.window.destroy()
        
    def on_save_button_clicked(self, button=None, data=None):
       # try:
            
            feed = self.xml.get_widget('entry1').get_text()
            self.window.destroy()
            addFeed(feed).start()
         
class addFeed(Thread):
    def __init__(self, feed):        
        self.feed = feed
        Thread.__init__(self)
    def run(self):
        try:
            req = urllib2.Request ('http://www.google.com/reader/api/0/token')
            f = urllib2.urlopen (req)
            token = f.read()
            
            data = { 's' : 'feed/' + self.feed, 'T' : token, 'ac' : 'subscribe'}
            data = urllib.urlencode (data)
            url = 'http://www.google.com/reader/api/0/subscription/edit?client=contact:' + grnotify_app.user
            req = urllib2.Request (url, data)
            f = urllib2.urlopen (req)
            grnotify_app.refresh()
        except:
            pass
        
class DBusReader(dbus.service.Object):
  @dbus.service.method("org.gnome.feed.Reader", 
                        in_signature="s", out_signature="b")
  def Subscribe(self, url):
    try:
      req = urllib2.Request('http://www.google.com/reader/api/0/token')
      f = urllib2.urlopen(req)
      token = f.read()
      
      data = {'s': 'feed/' + url, 'T': token, 'ac': 'subscribe'}
      data = urllib.urlencode(data)
      req = urllib2.Request('http://www.google.com/reader/api/0/subscription/edit?client=contact:' + grnotify_app.user, data)
      f = urllib2.urlopen (req)

      grnotify_app.refresh()

      return True
    except:
      return False
    
class configure_window:
    def __init__(self):
    #Set variables
        CONFIG = '/usr/share/grnotify/'

    #Create the dialog
        self.gladefile = CONFIG + "config.glade"
        self.xml = gtk.glade.XML(self.gladefile)  
        self.xml.signal_autoconnect(self)
        self.window = self.xml.get_widget('main_window')

    #Set the dialog title
        self.window.set_title('GrNotify (version ' + VERSION + ')')

    #Set the default username / password and waitTime values from the config file
        if grnotify_app.user != '' and grnotify_app.passwd != '':
            self.xml.get_widget('username_entry2').set_text(grnotify_app.user.strip())
            self.xml.get_widget('password_entry2').set_text(grnotify_app.passwd.strip())
        self.xml.get_widget('spinbutton1').set_text( str( ( grnotify_app.waitTime - grnotify_app.waitTime % 60 ) / 60) )
        self.xml.get_widget('spinbutton2').set_text( str( grnotify_app.waitTime % 60 ) )
        self.xml.get_widget('spinbutton3').set_text( str( grnotify_app.numberFeeds ) )
        if( grnotify_app.showCounter == True ):	
            self.xml.get_widget('showcounter1').set_active(1)
        if grnotify_app.showNotification == True:
            self.xml.get_widget('showpopups1').set_active(1)
        #Set the appropriate images to the icon chosers!!!		
        self.xml.get_widget('imagechooseiconnew2').set_from_file(grnotify_app.iconNew)
        self.xml.get_widget('buttonchooseiconnew2').connect("clicked", self.iconclicked, "new")
        self.xml.get_widget('imagechooseiconnonew2').set_from_file(grnotify_app.iconNoNew)
        self.xml.get_widget('buttonchooseiconnonew2').connect("clicked", self.iconclicked, "nonew")
        self.xml.get_widget('imagechooseiconbroken2').set_from_file(grnotify_app.iconBroken)
        self.xml.get_widget('buttonchooseiconbroken2').connect("clicked", self.iconclicked, "broken")
        self.xml.get_widget('combobox2').set_active(not grnotify_app.openReader)
	self.xml.get_widget('autohide').set_active(grnotify_app.autoHide)
	self.xml.get_widget('gnomekeyring').set_active(grnotify_app.useKeyRing)
        self.xml.get_widget('spinbutton4').set_text( str( grnotify_app.numberTitles ) )
        self.fileiconbroken = ''
        self.fileiconnew = ''
        self.fileiconnonew = ''

    def on_reset_button_clicked(self, widget, data=None):
        self.xml.get_widget('imagechooseiconnew2').set_from_file('/usr/share/pixmaps/grnotify/new.gif')
        self.fileiconnew = 'reset'
        self.xml.get_widget('imagechooseiconnonew2').set_from_file('/usr/share/pixmaps/grnotify/nonew.gif')
        self.fileiconnonew = 'reset'
        self.xml.get_widget('imagechooseiconbroken2').set_from_file('/usr/share/pixmaps/grnotify/broken.gif')
        self.fileiconbroken = 'reset'

    def iconclicked(self, widget, data=None):
        self.fileselect = gtk.FileChooserDialog(title='Pick a new icon for ' + data.capitalize(),  parent=None,
                                   action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                   buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
        self.fileselect.set_icon_from_file('/usr/share/pixmaps/grnotify/nonew.gif')
        self.fileselect.set_default_response(gtk.RESPONSE_OK)
        filter = gtk.FileFilter()
        filter.set_name("Images")
        filter.add_mime_type("image/png")
        filter.add_mime_type("image/gif")
        filter.add_pattern("*.png")
        filter.add_pattern("*.gif")
        filter.add_pattern("*.tif")
        filter.add_pattern("*.xpm")

        self.fileselect.add_filter(filter)

        response = self.fileselect.run()
        
        if response == gtk.RESPONSE_OK:
            self.iconget(widget,data)
        elif response == gtk.RESPONSE_CANCEL:
            self.fileselect.destroy()
        
    def iconget(self, widget, data=None):
        filename = self.fileselect.get_filename()
        self.fileselect.destroy()
        
        if(not filename.endswith('.gif') and not filename.endswith('.png') and not filename.endswith('.xpm')):
            return
        
        if(not os.stat(filename).st_size > 0):
            return
        
        if ( data == 'new' ):
            gtk.gdk.pixbuf_new_from_file(filename).scale_simple(24, 24, gtk.gdk.INTERP_NEAREST).save(os.path.join(os.environ['HOME'], '.grnotify/newtemp.png'), "png", {})
            self.fileiconnew = 'changed'
        elif ( data == 'nonew' ):
            gtk.gdk.pixbuf_new_from_file(filename).scale_simple(24, 24, gtk.gdk.INTERP_NEAREST).save(os.path.join(os.environ['HOME'], '.grnotify/nonewtemp.png'), "png", {})
            self.fileiconnonew = 'changed'
        else:
            gtk.gdk.pixbuf_new_from_file(filename).scale_simple(24, 24, gtk.gdk.INTERP_NEAREST).save(os.path.join(os.environ['HOME'], '.grnotify/brokentemp.png'), "png", {})
            self.fileiconbroken = 'changed'
        self.xml.get_widget('imagechooseicon' + data + '2').set_from_file(os.path.join(os.environ['HOME'], '.grnotify/' + data + 'temp.png'))

    def get_info(self):	
        grnotify_app.user = self.xml.get_widget('username_entry2').get_text()
        grnotify_app.passwd = self.xml.get_widget('password_entry2').get_text()
        grnotify_app.waitTime =int( self.xml.get_widget('spinbutton1').get_text()) * 60
        grnotify_app.waitTime += int( self.xml.get_widget('spinbutton2').get_text())
        if (grnotify_app.waitTime < 30):
            grnotify_app.waitTime = 30
        if( self.fileiconnew == 'changed' ):
            gtk.gdk.pixbuf_new_from_file(os.path.join(os.environ['HOME'], '.grnotify/newtemp.png')).save(os.path.join(os.environ['HOME'], '.grnotify/iconnew.png'), "png", {})
            grnotify_app.iconNew = os.path.join(os.environ['HOME'], '.grnotify/iconnew.png')
        if( self.fileiconnonew == 'changed' ):
            gtk.gdk.pixbuf_new_from_file(os.path.join(os.environ['HOME'], '.grnotify/nonewtemp.png')).save(os.path.join(os.environ['HOME'], '.grnotify/iconnonew.png'), "png", {})
            grnotify_app.iconNoNew = os.path.join(os.environ['HOME'], '.grnotify/iconnonew.png')
        if (self.fileiconbroken == 'changed'):
            gtk.gdk.pixbuf_new_from_file(os.path.join(os.environ['HOME'], '.grnotify/brokentemp.png')).save(os.path.join(os.environ['HOME'], '.grnotify/iconbroken.png'), "png", {})
            grnotify_app.iconBroken = os.path.join(os.environ['HOME'], '.grnotify/iconbroken.png')
        if (self.fileiconnew == 'reset' or self.fileiconnew == ''):
            grnotify_app.iconNew = '/usr/share/pixmaps/grnotify/new.gif'
            grnotify_app.iconNoNew = '/usr/share/pixmaps/grnotify/nonew.gif'
            grnotify_app.iconBroken = '/usr/share/pixmaps/grnotify/broken.gif'
        grnotify_app.numberFeeds = int (self.xml.get_widget('spinbutton3').get_text())
        grnotify_app.showCounter = self.xml.get_widget('showcounter1').get_active() 
        grnotify_app.showNotification = self.xml.get_widget('showpopups1').get_active() 
        grnotify_app.openReader = not self.xml.get_widget('combobox2').get_active()
	grnotify_app.autoHide = self.xml.get_widget('autohide').get_active()
	grnotify_app.useKeyRing = self.xml.get_widget('gnomekeyring').get_active()
        grnotify_app.numberTitles = int (self.xml.get_widget('spinbutton4').get_text())

    def on_save_button_clicked(self, button=None, data=None):
    #Get global access to the config_changed variable
        #Aquire the new data
        self.get_info()	

        #Save the new data to the config file
        grnotify_app.saveConfig()
        grnotify_app.refresh(forced=True)

        #Close the dialog
        self.window.destroy()

    def on_close_button_clicked(self, button=None, data=None):
    #Close the dialog
        self.window.destroy()
    
if __name__ == "__main__" :
    gtk.gdk.threads_init()
    
    # create the grnotify object (and icon)
    
    #readConfig() # fix by Eric Lembregts -> needed to know where the icon's are located!!
    grnotify_app = grnotify()
    grnotify_app.start()
    mainloop = gobject.MainLoop()

    # Make DBus object
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    session_bus = dbus.SessionBus()
    name = dbus.service.BusName("org.gnome.feed.Reader", session_bus)
    reader = DBusReader(session_bus, '/org/gnome/feed/Reader')
    mainloop = gobject.MainLoop()
    
    gtk.main()
