#!/usr/bin/env python
#
# $Id: AppletRun,v 1.16 2004/05/21 16:28:23 stephen Exp $

import findrox; findrox.version(1, 9, 12)
import rox
import rox.choices
import rox.options
import rox.applet
import rox.loading
import rox.InfoWin
import rox.Menu
g=rox.g

import sys

import os.path
import os
from stat import *
import string

from mailers import Mailer
from selmailer import SelectMailer
from Checker import getCheckers
from checkwin import CheckWin
from my_support import *
from SendFile import SendFile

def mail_file():
    username=os.getenv("LOGNAME")
    dmf="/var/mail/"+username
    return os.getenv("MAIL", dmf)

mailfile=mail_file()
app_dir=os.path.dirname(sys.argv[0])

# Get the defined mailers
mailers=None
fname=rox.choices.load('Mail', 'mailers.xml')
if fname!=None:
    mailers=Mailer.read_from(Mailer('dummy', ''), fname)
else:
    elm=Mailer('elm', '/usr/local/bin/elm', read='xterm -e %s')
    mailx=Mailer('mailx', '/usr/bin/mailx', read='xterm -e %s')
    fname=rox.choices.save('Mail', 'mailers.xml', 1)
    mailers=[mailx, elm]
    elm.write_to(mailers, fname)

mailer=mailers[0]

# Get the list of programs to check for or collect mail
fname=rox.choices.load('Mail', 'check.xml')
if fname!=None:
    checkers=getCheckers(fname)
else:
    checkers=None

rox.setup_app_options('Mail')

check_out=rox.options.Option('CheckOutgoingQ', 0)
beep=rox.options.Option('BeepForNew', 1)
rox.app_options.notify()

def out_queue():
    try:
        mailq=os.popen('mailq', 'r')
    except:
        return

    lines=mailq.readlines()
    try:
        # sendmail
        fline=lines[0].strip()
        op=fline.find('(')
        fline=fline[op+1:]
        cl=fline.find(' ')
        return int(fline[:cl])
    except:
        pass

    try:
        # postfix
        lline=lines[-1].strip()
        if lline[:3]!='-- ':
            return
        words=lline.split()
        return int(words[-2])
    except:
        pass

menu_def=[
    ('/Info', 'show_infowin', '<StockItem>', '', g.STOCK_DIALOG_INFO),
    ('/sep', '', '<Separator>'),
    ('/Options...', 'show_opts', '<StockItem>', '', g.STOCK_PREFERENCES),
    ('/sep', '', '<Separator>'),
    ('/Select mailer', 'show_sel_mailer', ''),
    ('/Check mail programs', 'show_checker_win', ''),
    ('/sep', '', '<Separator>'),
    ('/Quit', 'do_quit', '<StockItem>', '', g.STOCK_QUIT)
    ]

# Make our applet
class MailApplet(rox.applet.Applet, rox.loading.XDSLoader):
    def __init__(self, xid, app_dir, mailers, checkers):
        rox.applet.Applet.__init__(self, xid)
        rox.loading.XDSLoader.__init__(self, None)

        self.mail=-1
        self.app_dir=app_dir
        self.mailers=mailers
        self.checkers=checkers

        self.set_border_width(4)
        vbox=g.VBox()
        self.add(vbox)
        vbox.show()
        
        ebox=g.EventBox()
        ebox.set_events(g.gdk.BUTTON_PRESS_MASK | g.gdk.BUTTON_RELEASE_MASK)
        vbox.add(ebox)

        view=g.HBox()
        ebox.add(view)

        self.nomail_pixmap=g.Image()
        self.nomail_pixmap.set_from_file(app_dir+"/pixmaps/nomail.xpm")
        self.mail_pixmap=g.Image()
        self.mail_pixmap.set_from_file(app_dir+"/pixmaps/mail.xpm")

        view.add(self.mail_pixmap)
        view.add(self.nomail_pixmap)

        self.infoline=g.Label('')
        vbox.add(self.infoline)
        self.infoline.show()

        rox.Menu.set_save_name('Mail')
        self.menu=rox.Menu.Menu('main', menu_def)

        
        def check_child(pid):
            res=os.waitpid(pid, os.WNOHANG);
            if res[0]>0:
                return 0
            return 1
    
        def click(widget, event, self):
            if event.button==1:
                pid=run_prog(app_dir+"/AppRun")
                if pid>0:
                    g.timeout_add(1000, check_child, pid)
                return 1
            elif event.button==3:
                #self.menu.popup(None, None, None, event.button, event.time)
                self.menu.popup(self, event, self.position_menu)
                return 1
            return 0

        ebox.connect("button_press_event", click, self)

        self.tag=g.timeout_add(5000, self.update)

        if self.checkers!=None:
            for ch in self.checkers:
                ch.schedule()
                
    def show_sel_mailer(self):
        sm=SelectMailer(mailers)
        sm.set_callback(self.select_mailer)
        sm.show()
            
    def show_checker_win(self):
        cw=CheckWin(checkers)
        cw.show()
            
    def show_infowin(self):
        iw=rox.InfoWin.infowin('Mail')
        
    def show_opts(self):
        rox.edit_options()

    def do_quit(self):
        self.hide()
        self.destroy()
        
    def select_mailer(self, mailer, *args):
        if mailer!=None:
            try:
                i=self.mailers.index(mailer)
            except:
                i=-1
            if i>0:
                if i==len(mailers)-1:
                    self.mailers=[mailer]+self.mailers[:i]
                else:
                    self.mailers=[mailer]+self.mailers[:i]+self.mailers[i+1:]
            self.mailers[0].write_to(self.mailers, rox.choices.save('Mail', 'mailers.xml', 1))

    def update(self):
        if file_size(mailfile)>0:
            if self.mail!=1:
                self.nomail_pixmap.hide()
                self.mail_pixmap.show()
                self.mail=1
                if beep.int_value:
                    g.gdk.beep()
            nin=count_from(mailfile)
        else:
            if self.mail!=0:
                self.mail_pixmap.hide()
                self.nomail_pixmap.show()
                self.mail=0      
            nin=0
        if check_out.int_value:
            nout=out_queue()
        else:
            nout=0
        if nout:
            self.infoline.set_text('%d/%d' % (nin, nout))
        elif nin:
            self.infoline.set_text(str(nin))
        else:
            self.infoline.set_text("")
        return g.TRUE

    def xds_load_from_file(self, path):
        sf=SendFile(path)
        sf.show()

# Show everything and wait for events...
try:
    plug=MailApplet(sys.argv[1], app_dir, mailers, checkers)

    plug.show_all()
    plug.update()
    rox.mainloop()
    
except:
    rox.report_exception()


