#!/usr/bin/env python2.5
# -*- coding: iso-8859-15 -*-
# 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 3 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, write to the Free Software 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
#
# Written and Copyright - Rick Cull 2009.
#
#
# echo "user ALL = NOPASSWD: /bin/cp /home/user/.advoid/orighosts /etc/hosts" 
#                                            >> /etc/sudoers 
# echo "user ALL = NOPASSWD: /bin/cp /home/user/.advoid/tmphost /etc/hosts" 
#                                            >> /etc/sudoers 
# will need to go in deb postinstall script to allow cp a file to /etc/hosts

# Hostfiles for settings page
#http://pgl.yoyo.org/adservers/serverlist.php?hostformat=hosts&showintro=0&startdate%5Bday%5D=&startdate%5Bmonth%5D=&startdate%5Byear%5D=&mimetype=plaintext
#
#http://hostsfile.mine.nu/Hosts


import gtk 
import sys
import os 
import shutil 
import pango
from gtk import gdk 
import gobject 
from urllib import urlretrieve 
from subprocess import *
from stat import *
import time,datetime
import fileinput
import ConfigParser

Has_hildon=False

try:
    import hildon,osso
    Has_hildon=True
except:
    pass


class Advoid():
    
#-------------------------------------------------------------------------------

    def Settings(self,n):

        def Exit(n):

            servers=''
            for f in self.servers:
                servers=servers+f+";"

            servers=servers[:-1]

            # reset Variables iaw settings screen 

            self.fbot=int(loscale.get_value())
            self.fsize=int(defscale.get_value())
            self.ftop=int(upscale.get_value())
            self.ChunkSize=int(chunkentry.get_text())
            self.credits=credcheck.get_active()
            self.fullscreen=fullcheck.get_active()

            # rewrite settings 

            self.config.set('advoid','show_credits',self.credits)
            self.config.set('advoid','start_full',self.fullscreen)
            self.config.set('advoid','chunksize',self.ChunkSize)
            self.config.set('advoid','fupper',str(self.ftop))
            self.config.set('advoid','default_font_size',str(self.fsize))
            self.config.set('advoid','flower',str(self.fbot))
            self.config.set('advoid','servers',servers)
            conf=open(self.HOME+'/.advoid/settings','wb')
            self.config.write(conf)

            self.CurrServer=self.servers[CBox.get_active()]
            dialog.destroy()

        if Has_hildon:
            dialog=hildon.Window()
        else:
            dialog=gtk.Window()

        dialog.set_keep_above(True)
        dialog.set_title('Settings') 
        dialog.set_resizable(False)
        dialog.set_modal(True)

        if self.fullscreen and Has_hildon: 
            dialog.fullscreen()
        else:
            dialog.set_size_request(800,480)

        elabel=gtk.Label("Default Adserver")
        CBox = gtk.combo_box_new_text()
        for f in self.servers:
            CBox.append_text(f.split("/")[2])
        CBox.set_active(0)

        uplab=gtk.Label("Upper")
        uplab.show()
        upadj=gtk.Adjustment(self.ftop,self.fsize,self.ftop+10,1,0,0)
        upscale=gtk.HScale(upadj)
        upscale.set_draw_value(True)
        upscale.set_digits(0)

        deflab=gtk.Label("Default")
        deflab.show()
        defadj=gtk.Adjustment(self.fsize,self.fbot-4,self.ftop+10,1,0,0)
        defscale=gtk.HScale(defadj)
        defscale.set_draw_value(True)
        defscale.set_digits(0)

        lolab=gtk.Label("Lower")
        lolab.show()
        loadj=gtk.Adjustment(self.fbot,self.fbot-4,self.fsize,1,0,0)
        loscale=gtk.HScale(loadj)
        loscale.set_draw_value(True)
        loscale.set_digits(0)
 
        chunklab=gtk.Label("List Chunk Size")
        chunkentry=gtk.Entry()
        chunkentry.set_text(str(self.ChunkSize))
        fullcheck=gtk.CheckButton()
        fullcheck.set_active(self.fullscreen)
        fulllab=gtk.Label("Start Fullscreen")
        credcheck=gtk.CheckButton()
        credcheck.set_active(self.credits)
        credlab=gtk.Label("Show Credits")
        topbox=gtk.HBox(True,0)
        tophbox=gtk.HBox(True,0)
        topbox.pack_start(tophbox,True,True,0)
        toplbox=gtk.VBox(True,0)
        toplbox.pack_start(elabel,True,True,0)
        toprbox=gtk.VBox(True,0)
        toprbox.pack_start(CBox,True,True,0)
        tophbox.pack_start(toplbox,True,True,0)
        tophbox.pack_start(toprbox,True,True,0)
        botbox=gtk.HBox(True,0)
        lbox=gtk.VBox(True,0)
        rbox=gtk.VBox(True,0)
        rbox1=gtk.HBox(True,0)
        rbox1.pack_start(chunklab,False,False,10)
        rbox1.pack_end(chunkentry,False,False,10)
        rbox2=gtk.HBox(True,0)
        rbox2.pack_start(fulllab,False,False,10)
        rbox2.pack_end(fullcheck,False,False,10)
        rbox3=gtk.HBox(True,0)
        rbox3.pack_start(credlab,False,False,10)
        rbox3.pack_end(credcheck,False,False,10)

        vbox=gtk.VBox()
        vbox.pack_start(topbox,False,False,10)
        vbox.pack_start(botbox,True,True,10)

        opframe=gtk.Frame("List Font Sizes")
        fontbox=gtk.VBox(True,0)
        fontbox1=gtk.HBox(True,0)
        fontbox2=gtk.HBox(True,0)
        fontbox3=gtk.HBox(True,0)
        fontbox.pack_start(fontbox1,True,True,0)
        fontbox.pack_start(fontbox2,True,True,0)
        fontbox.pack_start(fontbox3,True,True,0)

        upbox=gtk.HBox(False,0)
        rupbox=gtk.HBox(True,0)
        upbox.pack_start(uplab,False,False,10)
        rupbox.pack_end(upscale,True,True,10)
        upbox.show_all()
        rupbox.show_all()
        defbox=gtk.HBox(False,0)
        rdefbox=gtk.HBox(True,0)
        defbox.pack_start(deflab,False,False,10)
        rdefbox.pack_end(defscale,True,True,10)
        defbox.show_all()
        lobox=gtk.HBox(False,0)
        rlobox=gtk.HBox(True,0)
        lobox.pack_start(lolab,False,False,10)
        rlobox.pack_end(loscale,True,True,10)
        lobox.show_all()

        fontbox1.pack_start(upbox,True,True,0)
        fontbox1.pack_start(rupbox,True,True,0)
        fontbox2.pack_start(defbox,True,True,0)
        fontbox2.pack_start(rdefbox,True,True,0)
        fontbox3.pack_start(lobox,True,True,0)
        fontbox3.pack_start(rlobox,True,True,0)
        fontbox.show_all()        
        opframe.add(fontbox)
        opframe.show_all()

        rbox.pack_start(rbox1,True,True,0)
        rbox.pack_start(rbox2,True,True,0)
        rbox.pack_start(rbox3,True,True,0)
        lbox.pack_start(opframe,True,True,0)
        botbox.pack_start(lbox,True,True,0)
        botbox.pack_start(rbox,True,True,0)
        vbox.show_all()

        self.Qimage=gtk.Image()
        self.Qimage.set_from_file(self.ImHome+'/go-previous.png')
        self.Qlabel=gtk.Label("Return")
        self.Qbutton=gtk.Button()
        self.Qbox=gtk.HBox(False,0)
        self.Qbox.pack_start(self.Qimage,False,False,0)
        self.Qbox.pack_start(self.Qlabel,False,False,0)
        self.Qbox.show()  
        self.Qbutton.add(self.Qbox)
        self.Qbutton.show()
        self.Qbutton.connect("clicked",Exit)
        self.Qbbox=gtk.HBox(True,0)

        self.bbox=gtk.HBox()
        self.bbox.pack_end(self.Qbutton,False,False,0)
        self.bbox.show_all()
        vbox.pack_start(self.bbox,False,False,0)
        dialog.add(vbox)
        dialog.show_all()

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

    def Display_Em(self,Store):
    
       #---------------------------------------

        def Sel(*args): 
            """ Callback for 'Selection Changed' """
            Debutton.set_sensitive(True)
            if self.CurrStore.get_iter_first() is None: return
            (model,self.PEiter) = self.PEsel.get_selected()
            if self.PEiter != None:
                self.PEpath=model.get_path(self.PEiter)
                self.Currdel = model.get_value(self.PEiter, 0)

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

        def Exit(n):
            if Store == "PE" : self.PEFile.close()
            if Store == "DE" : self.DEFile.close()
            if Store == "DL" : self.DLFile.close()
            self.DAWindow.remove(self.DAview)      
            Dialog.destroy()
            return True
        # --------------------------------------
               
        if Has_hildon:
            Dialog=hildon.Window()
        else:
            Dialog=gtk.Window()


        Dialog.set_keep_above(True)
        if Store == "PE" : Dialog.set_title="Personal Additions"
        if Store == "DE" : Dialog.set_title="System Settings"
        if Store == "DL" : Dialog.set_title="Downloaded File"
        Dialog.set_modal(True)

        if self.fullscreen and Has_hildon: 
            Dialog.fullscreen()
        else:
            Dialog.set_size_request(800,480)

        Dialog.connect("key-press-event",self.on_key_press)

        vbox=gtk.VBox(False,0)
        Displaybox=gtk.VBox(True,0)
        
        self.Displayframe=gtk.Frame()
        self.Displayframe.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
        self.DAWindow = gtk.ScrolledWindow()
        self.DAWindow.set_border_width(1)
        self.DAWindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self.Displayframe.add(self.DAWindow)
        self.DAWindow.add(self.DAview)      
        self.DAview.set_model(self.CurrStore)
        self.PEsel.connect('changed',Sel)
        Displaybox.pack_start(self.Displayframe,True,True)
        vbox.pack_start(Displaybox,True,True,0)
 

        self.Maimage=gtk.Image()
        self.Maimage.set_from_file(self.ImHome+'/gtk-refresh.png')
        self.Malabel=gtk.Label("       More .....")
        self.Mabox=gtk.HBox(False,0)
        self.Mabox.pack_start(self.Maimage,True,False,0)
        self.Mabox.pack_start(self.Malabel,True,False,0)
        self.Mabox.show()  
        self.Mabutton=gtk.Button() 
        self.Mabutton.add(self.Mabox)
        self.Mabutton.show()
        self.Mabutton.connect("clicked",self.Another_chunk)

        self.DEimage=gtk.Image()
        self.DEimage.set_from_file(self.ImHome+'/gtk-delete.png')
        self.DElabel=gtk.Label("Delete Selected")
        self.Debox=gtk.HBox(False,0)
        self.Debox.pack_start(self.DEimage,True,False,0)
        self.Debox.pack_start(self.DElabel,True,False,0)
        self.Debox.show()  
        Debutton=gtk.Button()
        Debutton.add(self.Debox)
        Debutton.show()
        Debutton.connect("clicked",self.Delete_Selected,Store)

        self.Ret=gtk.Button("Return")
        self.Ret.connect("clicked",Exit)

        self.Mabbox=gtk.HBox()
        self.Mabbox.pack_end(self.Ret,True,True,0)
        self.Mabbox.pack_end(Debutton,True,True,0)
        self.Mabbox.pack_end(self.Mabutton,True,True,0)
        self.Mabbox.show()

        Debutton.set_sensitive(False)
        vbox.pack_start(self.Mabbox,False,False,0)
 
        Dialog.add(vbox)
        vbox.show_all()
        Dialog.show_all()
        if Store == "DE" : Debutton.hide()


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

    def Update(self):
        """
            Refresh Gui 
        """
        while gtk.events_pending():
            gtk.main_iteration()
    
#-------------------------------------------------------------------------------

    def Clear(self):
        self.CurrStore.clear()
        self.DAview.set_model(None)
        for f in self.DAview.get_columns():
            self.DAview.remove_column(f)

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

    def do_Lists(self,n,Title,File,Store):
        """
            read files one 8K chunk at a time and display in relevant view
        """
        self.CurrType=Store

        self.HO_Heads = [Title]
        Line = ""

        if File is not None:
            self.MessLab.set_text("")
            self.Update()
            self.Clear()
            self.HO_Tcell=self.ListStore(self.HO_Heads,self.DAview,self.CurrStore,[],[])
            self.DAview.show()

        # -------------------Downloads-------------------

        if Store == "DL":

            if File is not None: self.DLFile=open(File,'r')  # need to open if new 

            Chunk = self.DLFile.readlines(self.ChunkSize)     # get 8k chunk
            if not Chunk: self.DLFile.close()

        # -------------------Personal--------------------

        elif Store == "PE":

            if File is not None: self.PEFile=open(File,'r') 

            Chunk = self.PEFile.readlines(self.ChunkSize)       
            if not Chunk: 
                self.PEFile.close()

        # -------------------Default----------------------

        elif Store == "DE":
            if File is not None: self.DEFile=open(File,'r') 

            Chunk = self.DEFile.readlines(self.ChunkSize)       
            if not Chunk: self.DEFile.close()

        for Line in Chunk:                     # add lines in chunk to store
 
            if Line.startswith("#"): continue

            if ( Line.endswith("\r\n")): 
                Line=Line[:-2]
            else: 
                Line=Line[:-1]

            if not ( Line.startswith("#") or Line.rstrip() == '' ):
                Bit=Line.split()
                try:
                    piter=self.CurrStore.append([Bit[1]])           
                except:
                    print repr(Bit)
                    continue
            else:
                tmp=[]
                tmp.append(Line)
                piter=self.CurrStore.append(tmp)     
                      
        if File is not None :
            if Chunk:
#                self.DAview.set_model(self.CurrStore)
#                self.PEsel.connect('changed',self.Sel)
                self.Display_Em(Store)
            else:
                self.MessLab.set_markup(self.red +\
                          "There are no entries to display !! </span>")
            
 
#-------------------------------------------------------------------------------

    def ListStore(self,Headers,view,store,Col,cell):
        """ 
            Create liststore and tableview 
        """
        view.set_model(store)
        for i in range(len(Headers)):
            Col.append(gtk.TreeViewColumn(Headers[i]))
            Col[i].set_expand(True)
            Col[i].set_clickable(True)
            view.append_column(Col[i])
            cell.append(gtk.CellRendererText())
            Col[i].pack_start(cell[i])
            Col[i].add_attribute(cell[i], 'text', i)

        view.set_headers_visible(True)
        view.set_rules_hint(True)
        return cell

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

    def Another_chunk(self,widget):
        """
            read another chunk from file - callback from 'More' button
        """
        if self.CurrType == "DL":
            self.do_Lists("","Downloaded",None,self.CurrType)
        elif self.CurrType == "PE":
            self.do_Lists("","Personal Additions",None,self.CurrType)
        elif self.CurrType == "DE":
            self.do_Lists("","Current System Settings",None,self.CurrType)

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

    def DoCopy(self,FromPath,ToPath):  
        """
            use Popen to do file coies to /etc/hosts
        """
        try:
            self.P = Popen(['sudo cp ' + FromPath + ' ' + ToPath ],
                            shell=True,
                            stdin=PIPE,
                            stdout=PIPE )
            sys.stdout.flush()
            time.sleep(1)
        except Exception,e:
            self.MessLab.set_markup(self.red +\
                      "Failed to copy file to /etc/hosts </span>"+repr(e))
        else:
            self.MessLab.set_markup(self.green+"Operation successfull</span>")
       
#-------------------------------------------------------------------------------

    def Fin(self,n,m):
        """
            Quit program
        """
        exit()

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

    def Orig_Hosts(self,n):
        """
            Copy orighists back to /etc/hosts
        """
        self.MessLab.set_markup(self.amber+"Reverting to Default.</span>")
        self.Update()
        self.DoCopy(self.HOME+"/.advoid/orighosts",'/etc/hosts') 
        self.do_Lists("","Current System Settings",'/etc/hosts',"DE")

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

    def Upd_Host_File(self,n):
        """
            Create a new Hostfile from original host, downloaded and personal files 
            in ~/.advoid and copy to /etc/hosts
        """
        self.MessLab.set_text("")
        self.MessLab.set_markup(self.amber+"Updating hostfile..</span>")

        self.Clear()
        self.Update()
 
        if os.path.exists(self.HOME+"/.advoid/tmphost"):
            try:
                os.remove(self.HOME+"/.advoid/tmphost")
            except Exception,e:
                self.MessLAb.set_markup(self.red+\
                         "Error removing"+self.HOME+"/.advoid/tmphost</span>")
        
        tmphost = open(self.HOME+"/.advoid/tmphost",'a')
        
        #----------------- Original Defaults ----------------------
        self.DEFile=open(self.HOME+"/.advoid/orighosts","r")
        Lines=self.DEFile.readlines()
        for Line in Lines: tmphost.write(Line)
        self.DEFile.close()        

        #------------------ Personal Additions ---------------------
        self.PEFile=open(self.HOME+"/.advoid/personal","r")
        Lines=self.PEFile.readlines()
        for Line in Lines: tmphost.write(Line)        
        self.PEFile.close()

        #------------------ Downloade File -------------------------
        self.DLFile=open(self.HOME+"/.advoid/downloaded","r")
        Lines=self.DLFile.readlines()
        for Line in Lines:   
            if Line.endswith("\r\n"):
                tmphost.write(Line[:-2]+"\n")
            else:
                tmphost.write(Line)
        self.DLFile.close
        
        Lines=""
        tmphost.close()
        
        self.DoCopy(self.HOME+"/.advoid/tmphost",'/etc/hosts')  
 
        self.do_Lists("","Current Sytem Settings",'/etc/hosts',"DE") 
 
#-------------------------------------------------------------------------------

    def Add_New_Url(self,n):
        """ 
            'Add button' callback. 
            Get contents of the entry and do some validation.
        """
 
        def Already_gotit(U,F):
            Found=False
            for line in fileinput.FileInput(F,inplace=1):
                print line,
                if U in line:
                    Found = True
            fileinput.close()
            return Found
 
        NewUrl=[]
        Entry=self.AddEntry.get_text()
        dname=self.HOME+"/.advoid/downloaded"
        fname=self.HOME+"/.advoid/personal"
        if Entry == "" or Entry is None:
            self.MessLab.set_markup(self.red+\
            "You must enter a new URL here !!!</span>")
        else:  
        
            # check if this url is already in downloaded   
            if Already_gotit(Entry,dname) or Already_gotit(Entry,fname):            
                self.MessLab.set_markup(self.red+\
                "This Url already exists in either downloaded or personal file</span>")
                return

            try:
                File=open(fname,'a')
                File.write("127.0.0.1 "+Entry+"\n")
            except Exception,e:
                self.MessLab.set_markup(self.red+\
                    "Error writing to "+self.HOME+"/.advoid/personal</span>")
            finally:
                File.close()
            NewUrl.append(Entry)
            self.CurrStore.append(NewUrl)
            self.AddEntry.set_text("")
#-------------------------------------------------------------------------------

    def download(self,n):
        """" 
            'Download New' callback 
            Get a new ad server host file from www.mvps.org, save and
            update liststore and view
        """
        self.MessLab.set_text("")
        self.Update()
        Message="Updating Ad blocking list from "+self.CurrServer.split("/")[2]+"...</span>"

        try:
            self.MessLab.set_markup(self.amber+Message)
                    
            self.Update()
            ret=urlretrieve(self.CurrServer,
                             self.HOME+"/.advoid/downloaded")
            sys.stdin.flush()
            sys.stdout.flush()
#            time.sleep(1)
            self.do_Lists("","Downloaded File ",self.HOME+'/.advoid/downloaded',"DL")
        except IOError :
            self.MessLab.set_markup(self.red+\
           "Unable to retrieve file. Check your internet connection !!!</span>")
            self.Update()
            ret = None
        else:
            self.MessLab.set_markup(self.green+\
                 "Update from "+self.CurrServer.split("/")[2]+" Complete</span>")
            self.Update()    
        
#-------------------------------------------------------------------------------

    def shot(self,n,Type="A",Res="80"):
         """ 
             Screenshot utility
             Using for devel purposes remove when dun
         """
#         time.sleep(5)
         t=datetime.datetime.now()
         fname="Shot"+str(int(time.mktime(t.timetuple())))+"."
         format = "jpeg"
         screenw = gtk.gdk.screen_width()
         screenh = gtk.gdk.screen_height()
         if Type == "A":
             root=gtk.gdk.screen_get_default()
             active = root.get_active_window()
             relativex, relativey, winw, winh, d = active.get_geometry() 
             screenw = winw + (relativex*2)
             screenh = winh + (relativey+relativex)
             screenposx, screenposy = active.get_root_origin()
         else :
             screenposx=0
             screenposy=0

         screenshot = gtk.gdk.Pixbuf.get_from_drawable(
                 gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,True,8,screenw,screenh),
                 gtk.gdk.get_default_root_window(),
                 gtk.gdk.colormap_get_system(),
                 screenposx, screenposy, 0, 0, screenw, screenh)
         screenshot.save(fname + format, format,  {"quality": Res})
         print "Taken"
            #-------------------------------------------------------------------------------

    def on_window_state_change(self,widget,event,*args):
        """ 
            Set window_in_fullscreen acording to state 
        """
        if event.new_window_state & gtk.gdk.WINDOW_STATE_FULLSCREEN:
            self.window_in_fullscreen = True
        else:
            self.window_in_fullscreen = False
            #-------------------------------------------------------------------------------

    def on_key_press(self,widget,event,*args):
        """ 
            Various key bindings 
        """
        #--------------------------------------------------------------------
        def Do_Settings():
            """
                Action font changes
            """
            Settings=gtk.settings_get_for_screen(gdk.screen_get_default())
            gtk.rc_parse_string(self.Style1 + str(self.fsize) + self.Style2)
            gtk.rc_reset_styles(Settings)

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

        if event.keyval == gtk.keysyms.F6:        # Toggle fullscreen

            if self.window_in_fullscreen:
                widget.unfullscreen()
#                self.window.unfullscreen()
                self.window_in_fullscreen = False
            else:
                widget.fullscreen()
#                self.window.fullscreen()
                self.window_in_fullscreen = True    

        if event.keyval == gtk.keysyms.F7:         # Increment Font size
            if self.fsize < self.ftop: 
                self.fsize += 2 
                Do_Settings()
            else: 
                return
            
        if event.keyval == gtk.keysyms.F8:         # Decrement Font size
            if self.fsize > self.fbot: 
                self.fsize -= 2 
                Do_Settings()
            else: 
                return
   
#-------------------------------------------------------------------------------

    def Delete_Selected(self,n,Which):
        """
            callback for 'Delete' button
        """
        def do_del():
            self.PEiter=self.CurrStore.get_iter(self.PEpath)        
            Iter=self.CurrStore.remove(self.PEiter)
            self.Update()
            for Line in fileinput.input(File,inplace=1):
                Line = Line.strip()
                if not self.Currdel in Line:
                    print Line
                
        if Which == "DL":       
            self.DLFile.close()
            File=self.HOME+"/.advoid/downloaded"
            do_del()
            self.DLFile=open(File,'r')
        elif Which == "PE":
            self.PEFile.close()
            File=self.HOME+"/.advoid/personal"
            do_del()
            self.PEFile=open(File,'r')
            

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

    def Credits(self):
        """
            Credits dialog
        """
        self.Idialog = gtk.Dialog(title='Credits',
                    buttons=("Dismiss", gtk.RESPONSE_OK))

        self.Idialog.set_border_width(2)
        self.Idialog.set_size_request(650,350)
        lwindow = gtk.ScrolledWindow()
        lwindow.set_shadow_type(gtk.SHADOW_IN)
        self.Idialog.vbox.pack_start(lwindow,True,True,0)
        Version="Advoid Version 0.9\n\n"
        self.mvps="The Ad blocking hostfile is downloaded from http://www.mvps.org/winhelp2002/ and is Licensed under the Creative Commons  Attribution-NonCommercial-ShareAlike License."

        Gpl=\
        """
Advoid allows you to update your system with a downloaded list of advert-servers from the internet.this results in blocking adverts from any browser used with the system.

There is also the option of adding any servers not currently included in this downloaded list - see the entrybox and button at the top of the main screen. 

Use 'Update my System' after any change ( ie new download or new personnal URL added ) or Use 'Revert to Default' to return to your original settings.

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 3 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, write to the Free Software Foundation, Inc., 
59 Temple Place, 
Suite 330, Boston, 
MA 02111-1307, 
USA.
     

Written and Copyright - Rick Cull 2009.
        
"""

        self.InfoLab=gtk.Label()
        self.InfoLab.set_line_wrap(True)
        self.InfoLab.set_justify(gtk.JUSTIFY_CENTER)
        self.Info_For_Lab='<i><span size="small">'+Version+Gpl+self.mvps+"\n\n"+self.Last+"</span></i>"

        self.InfoLab.set_markup(self.Info_For_Lab)
        lwindow.add_with_viewport(self.InfoLab)
        self.Idialog.show_all()

        result = self.Idialog.run()

        if result == gtk.RESPONSE_OK:
            self.Idialog.destroy()

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

    def Get_Settings(self):
        """ get all settings from ~/.advoid/settings """
        self.config.read(self.HOME+"/.advoid/settings")
        self.servers=self.config.get('advoid','servers').split(";")
        self.fsize=self.config.getint('advoid','default_font_size')
        self.ftop=self.config.getint('advoid','fupper')
        self.fbot=self.config.getint('advoid','flower')
        self.ChunkSize=self.config.getint('advoid','chunksize')
        self.fullscreen=self.config.getboolean('advoid','start_full')
        self.credits=self.config.getboolean('advoid','show_credits')

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

    def __init__(self):
        """
            Main
        """
        self.HOME=os.environ.get('HOME')
        self.ftop=32
        self.fbot=10
        self.fsize=18    
        self.ChunkSize=8192
        self.servers=""
        self.credits=True
        self.fullscreen=False
        self.window_in_fullscreen=False
        self.config=ConfigParser.ConfigParser()
        self.Get_Settings()
        self.CurrServer=self.servers[0]
        # PC or Tablet ???
        if Has_hildon:
            self.program=hildon.Program()
            self.program.__init__()
            self.window = hildon.Window()
        else:
            self.window = gtk.Window()

        if self.fullscreen and Has_hildon: 
            self.window.fullscreen()
#        else:
#           self.window.set_size_request(800,480)

        self.Style1=\
        """
        style "view-font"
        {
           GtkTreeView :: expander_size = 32
           GtkTreeView :: vertical_seperator = 32
           font_name = "Sans """
        self.Style2=\
        """ "
        }
        style "e-style"
        {
           font_name = "Sans 20"
        }
        class "GtkEntry" style "e-style"
        class "GtkTreeView" style "view-font" """
        gtk.rc_parse_string(self.Style1+str(self.fsize)+self.Style2)
    
        # Some Vars
        Types=[]
        Types.append(str)
        self.ImHome='/usr/share/pixmaps/advoid'
        self.DAview=gtk.TreeView()
        self.PEsel=self.DAview.get_selection() 
        self.PEsel.set_mode(gtk.SELECTION_SINGLE) 

        self.CurrStore=gtk.ListStore(*Types)
        self.PEpath=""
        self.CurrType=""
        self.DLFile=0
        self.PEFile=0
        self.DEFile=0
        self.PEiter=gtk.TreeIter
        self.Ydate=""
        self.red='<span foreground="red">'
        self.amber='<span foreground="orange">'
        self.green='<span foreground="#127E15">'
        self.Vis=False
        self.Loaded=False
        self.HO_Tcell=gtk.TreeView()
        self.MyFiles=["personal","downloaded"]

        # check ~/.advoid folder exists
        if not os.path.exists(self.HOME+"/.advoid"):
            try:
                os.mkdir(self.HOME+"/.advoid")
            except:
                print "Unable to create "+self.HOME+"/.advoid"
                exit()

        # Check needed files present.
        for f in self.MyFiles:
            File=self.HOME+"/.advoid/"+f
            if not os.path.exists(self.HOME+"/.advoid/"+f):
                try:
                    tmp=open(File,'w')
                    tmp.close()
                except Exception,e:
                    print "Unable to create "+f+"\n"+repr(e)
                    exit()
        
            
        # download date
        self.Dmode=os.stat(self.HOME+"/.advoid/downloaded")[ST_MTIME]
        self.Darr=time.gmtime(self.Dmode)

        self.Last="The Ad Blocking file was last downloaded - "+\
        str(self.Darr[3])+":"+str(self.Darr[4])+"  "+str(self.Darr[2])+\
        "-"+str(self.Darr[1])+"-"+str(self.Darr[0])

        self.window.connect("delete_event",self.Fin) 
        self.window.connect("key-press-event",self.on_key_press)
        self.window.connect("window-state-event",self.on_window_state_change) 

        self.CurrLab=gtk.Label("Enter new URL here.")
        self.InfLab=gtk.Label("")

        self.AddBox=gtk.HBox(False,0)
        self.AddTab=gtk.Table(2,3,False)
        self.AddBox.pack_start(self.AddTab,True,True,0)
        self.AddEntry=gtk.Entry()

        self.Adimage=gtk.Image()
        self.Adimage.set_from_file(self.ImHome+'/insert-link.png')
        self.AddButt=gtk.Button()
#        self.ABbox=gtk.VBox(False,0)
#        self.ABbox.pack_start(self.Adimage,False,False,1)
        self.AddButt.add(self.Adimage)
#        self.AddButt.connect("clicked",self.shot) 
        self.AddButt.connect("clicked",self.Add_New_Url)

        self.AddTab.attach(self.CurrLab,0,1,0,1,gtk.EXPAND,0,0,0)
        self.AddTab.attach(self.InfLab,1,3,0,1,gtk.EXPAND,0,0,0)
        self.AddTab.attach(self.AddEntry,0,2,1,2,gtk.FILL,gtk.FILL,0,2)
        self.AddTab.attach(self.AddButt,2,3,1,2,gtk.FILL,gtk.EXPAND,0,2)

        self.WindowBox=gtk.HBox(True,0)
        self.leftbox=gtk.HBox(True,0)
        self.leftframe=gtk.Frame()
        self.leftbox.pack_start(self.leftframe,True,True,0)

        self.rightbox=gtk.HBox(True,0)
        self.rightframe=gtk.Frame()
        self.rightbox.pack_start(self.rightframe,True,True,0)

        self.WindowBox.pack_start(self.leftbox,True,True,0)
        self.WindowBox.pack_start(self.rightbox,True,True,0)

        self.SEimage=gtk.Image()
        self.SEimage.set_from_file(self.ImHome+'/config.png')
        self.PEimage=gtk.Image()
        self.PEimage.set_from_file(self.ImHome+'/personal.png')
        self.DEimage=gtk.Image()
        self.DEimage.set_from_file(self.ImHome+'/computer.png')
        self.DLimage=gtk.Image()
        self.DLimage.set_from_file(self.ImHome+'/download.png')

        self.tbuttbox=gtk.VButtonBox()
        self.tbuttbox.set_layout(gtk.BUTTONBOX_EDGE)
        self.tbuttbox.set_spacing(5)
        self.Rbuttbox=gtk.VButtonBox()
        self.Rbuttbox.set_layout(gtk.BUTTONBOX_EDGE)
        self.Rbuttbox.set_spacing(5)

        self.DLButtLab=gtk.Label("Show Downloaded")
        self.DLButt=gtk.Button()
        self.DLbox=gtk.HBox(False,0)
        self.DLbox.pack_start(self.DLimage,False,False,0)
        self.DLbox.pack_start(self.DLButtLab,False,False,0)
        self.DLButt.add(self.DLbox)

        self.PEButtLab=gtk.Label("Show Personal")
        self.PEButt=gtk.Button()
        self.PEbox=gtk.HBox(False,0)
        self.PEbox.pack_start(self.PEimage,False,False,0)
        self.PEbox.pack_start(self.PEButtLab,False,False,0)
        self.PEButt.add(self.PEbox)

        self.DEButtLab=gtk.Label("Show System")
        self.DEButt=gtk.Button()
        self.DEbox=gtk.HBox(False,0)
        self.DEbox.pack_start(self.DEimage,False,False,0)
        self.DEbox.pack_start(self.DEButtLab,False,False,0)
        self.DEButt.add(self.DEbox)

        self.SEButtLab=gtk.Label("Settings")
        self.SEButt=gtk.Button()
        self.SEbox=gtk.HBox(False,0)
        self.SEbox.pack_start(self.SEimage,False,False,0)
        self.SEbox.pack_start(self.SEButtLab,False,False,0)
        self.SEButt.add(self.SEbox)

        self.DEButt.connect("clicked", 
                             self.do_Lists,
                             "Sytem Host File",
                             '/etc/hosts',
                             "DE")
        self.PEButt.connect("clicked", 
                             self.do_Lists,
                             "Personal Additions",
                             self.HOME+'/.advoid/personal',
                             "PE")
        self.DLButt.connect("clicked", 
                             self.do_Lists,
                             "Downloaded File",
                             self.HOME+'/.advoid/downloaded',
                             "DL") 
        self.SEButt.connect("clicked", 
                             self.Settings)

        self.tbuttbox.add(self.DLButt)
        self.tbuttbox.add(self.PEButt)
        self.Rbuttbox.add(self.DEButt)
        self.Rbuttbox.add(self.SEButt)
        self.leftframe.add(self.tbuttbox)
        self.rightframe.add(self.Rbuttbox)

        self.Deimage=gtk.Image()
        self.Deimage.set_from_file(self.ImHome+'/go-down.png')
        self.DefButtLab=gtk.Label("Revert to Default")
        self.DefButtLab.set_justify(gtk.JUSTIFY_CENTER)
        self.DefButt=gtk.Button()
        self.Debox=gtk.HBox(False,0)
        self.Debox.pack_start(self.Deimage,False,False,0)
        self.Debox.pack_start(self.DefButtLab,False,False,0)
        self.DefButt.add(self.Debox)
        self.DefButt.connect("clicked",self.Orig_Hosts)
        self.tbuttbox.add(self.DefButt)

        self.Doimage=gtk.Image()
        self.Doimage.set_from_file(self.ImHome+'/go-up.png')
        self.DoButtLab=gtk.Label("Update my System")
        self.DoButt=gtk.Button()
        self.Dbox=gtk.HBox(False,0)
        self.Dbox.pack_start(self.Doimage,False,False,0)
        self.Dbox.pack_start(self.DoButtLab,False,False,0)
        self.DoButt.add(self.Dbox)
        self.DoButt.connect("clicked",self.Upd_Host_File)
        self.Rbuttbox.add(self.DoButt)

        self.Eimage=gtk.Image()
        self.Eimage.set_from_file(self.ImHome+'/exit.png')
        self.EButtLab=gtk.Label("End Program")
        self.EButt=gtk.Button()
        self.Ebox=gtk.HBox(False,0)
        self.Ebox.pack_start(self.Eimage,False,False,0)
        self.Ebox.pack_start(self.EButtLab,False,False,0)
        self.EButt.add(self.Ebox)
        self.EButt.connect("clicked",lambda w: self.Fin(self.EButt,self.window))
        self.Rbuttbox.add(self.EButt)

        self.Upimage=gtk.Image()
        self.Upimage.set_from_file(self.ImHome+'/go-jump.png')
        self.UpButtLab=gtk.Label("Download New File")
        self.UpButt=gtk.Button()
        self.Ubox=gtk.HBox(False,0)
        self.Ubox.pack_start(self.Upimage,False,False,0)
        self.Ubox.pack_start(self.UpButtLab,False,False,0)
        self.UpButt.add(self.Ubox)
        self.UpButt.connect("clicked",self.download)
        self.tbuttbox.add(self.UpButt)

        self.tbox=gtk.VBox(False,0)
        self.window.add(self.tbox)

        self.mbox=gtk.VBox(False,0)
        self.MessLab=gtk.Label("")
         
        self.tbox.pack_start(self.AddBox,False,False,0)
        self.tbox.pack_start(self.WindowBox,True,True,0)
        self.mbox.pack_start(self.MessLab,False,False,0)
        self.tbox.pack_start(self.mbox,False,False,0)

        # Check if orighosts in .advoids else copy /etc/hosts
        if not os.path.exists(self.HOME+"/.advoid/orighosts"):
            self.DoCopy('/etc/hosts',self.HOME+"/.advoid/orighosts")

        self.window.show_all()
        mode=os.stat(self.HOME+"/.advoid/downloaded")[ST_MTIME]
        Arr=time.gmtime(mode)

        self.InfLab.set_text("Last Download - "+
            str(Arr[3])+":"+
            str(Arr[4])+"  "+
            str(Arr[2])+"/"+
            str(Arr[1])+"/"+
            str(Arr[0]))

        if self.credits:
            self.Credits()

    def run(self):
        gtk.main()

if __name__ == "__main__":
    try:
        osso_context = osso.Context("net.rcull.advoid","0.9",False)
    except Exception,e:
        if repr(e).find("NameError") == 0:
            pass
        else:
            print "Error when testing for osso"
    app=Advoid()
    app.run()
