## $Id: prefs.py,v 1.69 2001/10/10 12:13:52 kjetilja Exp $

## System modules
from gtk import *
from gnome.ui import *
from gnome.config import *
from posixpath import split
import os, glob

## Local import pwdmodules
import folderops, fileops, fonts


## Error messages from the GUI
err1 = """You must specify at least one account!"""
err2 = """You must specify a host for outgoing mail!"""
err3 = """Unable to create mail folder directory: \n %s"""

WIN_SIZE = 0
FLD_SIZE = 1
MSG_SIZE = 2
LST_SIZE = 3

## Name of the default account
DEF_ACC = "New account"

## Old GnomeUI modules have a typo here
class PFontPicker(GnomeFontPicker):
    def __init__(self, _obj=None):
        GnomeFontPicker.__init__(self, _obj)

    def get_font_name(self):
        import _gnomeui
        return _gnomeui.gnome_font_picker_get_font_name(self._o)
        
##
##
## Preferences class
##
##
class Preferences:
    ##
    ## Method __init__ (self)
    ##
    ##    Constructor for preferences class.
    ##
    ##
    def __init__(self):
        launch_preferences = 0
        if not has_section('pygmy/prefs'):
            launch_preferences = 1

        self.accounts = {}
        self.filepaths = {}
        account_names = get_vector('pygmy/prefs/account_names')
        for name in account_names:
            self.accounts[name] = get_vector('pygmy/accounts/%s' % name)
            if self.accounts[name][0][0] == '_':
                self.accounts[name] = map(lambda x: x[1:], self.accounts[name])
        self.defacc = get_string('pygmy/prefs/defacc') or ''
        
        self.usemailserver = get_bool('pygmy/prefs/usemailserver') or 0
        self.serverentry = get_string('pygmy/prefs/serverentry') or "smtp"
        self.usesendmail = get_bool('pygmy/prefs/usesendmail') or 0
        self.sendmailentry = get_string('pygmy/prefs/sendmailentry') or "/usr/lib/sendmail"
        self.external_cmd = get_string('pygmy/prefs/external_cmd') or ""
        self.invoke_at_startup = get_bool('pygmy/prefs/invoke_at_startup') or 0
        self.mailnotify = get_bool('pygmy/prefs/mailnotify') or 0
        self.addsig = get_bool('pygmy/prefs/addsig') or 0
        self.sigreply = get_string('pygmy/prefs/sigreply') or 'none'
        self.sigforward = get_string('pygmy/prefs/sigforward') or 'none'
        self.expand = get_bool('pygmy/prefs/expand') or 0
        self.confirmsend = get_bool('pygmy/prefs/confirmsend') or 0
        self.fillwidth = get_int('pygmy/prefs/fillwidth') or 74
        self.view_to = get_bool('pygmy/prefs/view_to') or 0
        self.view_cc = get_bool('pygmy/prefs/view_cc') or 0
        self.trash = get_bool('pygmy/prefs/trash') or 0
        self.default_folders = ('inbox', 'sent-mail', 'drafts', 'trash')
        self.filter_start = get_bool('pygmy/prefs/filter_start') or 0        
        self.gtkhtml = get_bool('pygmy/prefs/gtkhtml') or 0        

        self.citechar = get_string('pygmy/prefs/citechar') or ">"
        self.prefix = get_string('pygmy/prefs/prefix') or "Re:"
        self.forward = get_string('pygmy/prefs/forward') or "Fw:"

        self.usebuiltined = get_bool('pygmy/prefs/usebuiltined') or \
			    not get_bool('pygmy/prefs/useexternaled')
        self.externaledentry = get_string('pygmy/prefs/externaledentry') or "/usr/bin/vim"
        self.editorhints = get_string('pygmy/prefs/editorhints') or 'none'

	self.fld_font = get_string('pygmy/prefs/fld_font') or fonts.NORMAL_FONT
        self.sub_font = get_string('pygmy/prefs/sub_font') or fonts.NORMAL_FONT
	self.msg_font = get_string('pygmy/prefs/msg_font') or fonts.NORMAL_FONT
	self.compose_font = get_string('pygmy/prefs/compose_font') or fonts.NORMAL_FONT
        self.externaled_font = get_string('pygmy/prefs/externaled_font') or fonts.EXTERNALED_FONT

        default_sizes = [[560, 560], [170, 280], [520, 280], [10, 100, 290, 10, 20]]
        self.size = range(len(default_sizes))
        for index in range(len(default_sizes)):
            vec = get_vector('pygmy/geometry/win_%d' % index)
            vec = map(lambda x: int(x), vec)
            self.size[index] = vec or default_sizes[index]

        fp = get_vector('pygmy/prefs/default_filepaths')
        for name in fp:
            self.filepaths[name] = get_string('pygmy/filepaths/%s' % name)

        homedir = fileops.gethomedir()
        self.alistfile = get_string('pygmy/prefs/alistfile') or \
                         os.path.join(homedir, ".pygmy-adrlist")
        self.flistfile = get_string('pygmy/prefs/flistfile') or \
                         os.path.join(homedir, ".pygmy-filterlist")
        self.spoolfile = get_string('pygmy/prefs/spoolfile') or \
                         fileops.getmailfile()
        self.folders = get_string('pygmy/prefs/folders') or \
                       os.path.join(homedir, "Mail")

        self.more = get_bool('pygmy/prefs/moreheaders') or 0

        self.version = "0.5.13"

        if launch_preferences:
            p = PreferencesWindow(self)
            p.mainloop()


    ##
    ## Method save (self)
    ##
    ##    Save the current configuration.
    ##
    ##
    def save(self):
        set_bool('pygmy/prefs/filter_start', self.filter_start) 
        set_bool('pygmy/prefs/gtkhtml', self.gtkhtml) 
        set_string('pygmy/prefs/defacc', self.defacc)
        set_bool('pygmy/prefs/usemailserver', self.usemailserver) 
        set_string('pygmy/prefs/serverentry', self.serverentry)
        set_bool('pygmy/prefs/usesendmail', self.usesendmail)
        set_string('pygmy/prefs/sendmailentry', self.sendmailentry)
        set_string('pygmy/prefs/external_cmd', self.external_cmd)
        set_bool('pygmy/prefs/invoke_at_startup', self.invoke_at_startup)
        set_bool('pygmy/prefs/mailnotify', self.mailnotify)
        set_bool('pygmy/prefs/addsig', self.addsig)
        set_string('pygmy/prefs/sigreply', self.sigreply)
        set_string('pygmy/prefs/sigforward', self.sigforward)
        set_bool('pygmy/prefs/expand', self.expand)
        set_bool('pygmy/prefs/confirmsend', self.confirmsend)
        set_int('pygmy/prefs/fillwidth', self.fillwidth)
        set_bool('pygmy/prefs/view_cc', self.view_cc)
        set_bool('pygmy/prefs/view_to', self.view_to)
        set_bool('pygmy/prefs/trash', self.trash)
        set_string('pygmy/prefs/citechar', self.citechar)
        set_string('pygmy/prefs/prefix', self.prefix)
        set_string('pygmy/prefs/forward', self.forward)
        set_string('pygmy/prefs/fld_font', self.fld_font)
        set_string('pygmy/prefs/sub_font', self.sub_font)
        set_string('pygmy/prefs/msg_font', self.msg_font)
        set_string('pygmy/prefs/compose_font', self.compose_font)
        set_string('pygmy/prefs/externaled_font', self.externaled_font)
        set_string('pygmy/prefs/version', self.version)
        set_vector('pygmy/prefs/default_folders', self.default_folders)
        set_string('pygmy/prefs/alistfile', self.alistfile)
        set_string('pygmy/prefs/flistfile', self.flistfile)
        set_string('pygmy/prefs/spoolfile', self.spoolfile)
        set_string('pygmy/prefs/folders', self.folders)

	# editor preferences
        set_bool('pygmy/prefs/usebuiltined', self.usebuiltined )
        set_bool('pygmy/prefs/useexternaled', not self.usebuiltined )
        set_string('pygmy/prefs/externaledentry', self.externaledentry )
        set_string('pygmy/prefs/editorhints', self.editorhints )

        clean_section('pygmy/accounts')
        set_vector('pygmy/prefs/account_names', self.accounts.keys())
        for name in self.accounts.keys():
            set_vector('pygmy/accounts/%s' % name, map(lambda x: '_'+ x,
                                                       self.accounts[name][:]))
        clean_section('pygmy/geometry')
        index = 0
        for set in self.size:
            vec = map(lambda x: str(x), self.size[index])
            set_vector('pygmy/geometry/win_%d' % index, vec)
            index = index + 1

        clean_section('pygmy/filepaths')
        set_vector('pygmy/prefs/default_filepaths', self.filepaths.keys())
        for name in self.filepaths.keys():
            set_string('pygmy/filepaths/%s' % name, self.filepaths[name] or '' )

        set_bool('pygmy/prefs/moreheaders', self.more)

        sync()
        

##
##
## Preferences Window class
##
##
class PreferencesWindow:
    ##
    ## Method __init__ (self, prefs instance, parent window instance)
    ##
    ##    Constructor for preferences window.
    ##
    ##
    def __init__(self, prefs, parent=None):
        from gnome.zvt import ZvtTerm

        self.win = GnomeDialog(':Pygmy - Preferences', 'Ok', 'Cancel')
        self.vbox = self.win.vbox
        self.prefs = prefs
        self.dialogs = {}
        self.entry = prefs.accounts.copy()

        self.externaled_support = "writechild" in dir(ZvtTerm)
        if not self.externaled_support:
            self.prefs.usebuiltined = 0

        # Set parent window if supplied
        if parent != None:
            self.win.set_parent(parent)

	self.win.connect('delete_event', mainquit)
	self.win.connect('destroy', mainquit)
        self.win.connect('clicked', self.handle_callbacks)
        
        self.init_notebook()
        self.vbox.show()
        self.win.show()


    ##
    ## Method handle_callbacks (self, button, no)
    ##
    ##    Handle callbacks for the action buttons.
    ##
    ##
    def handle_callbacks(self, button, no):
        if no == 0:
            # Propagate configuration from the preferences window
            if self.entry.has_key(DEF_ACC):
                del self.entry[DEF_ACC]
            self.prefs.accounts = self.entry.copy()
            self.prefs.serverentry = self.serverentry.get_text()
            self.prefs.usemailserver = self.usemailserver.get_active()
            self.prefs.usesendmail = self.usesendmail.get_active()
            self.prefs.sendmailentry = self.sendmailentry.gtk_entry().get_text()
            self.prefs.folders = self.direntry.gtk_entry().get_text()
            self.prefs.spoolfile = self.spoolentry.gtk_entry().get_text()
            self.prefs.mailnotify = self.notify.get_active()
            self.prefs.trash = self.trash.get_active()
            self.prefs.expand = self.expand.get_active()
            self.prefs.addsig = self.addsig.get_active()
            self.prefs.sigreply = self.sigreply.get_menu().get_active().get_data("id")
            self.prefs.sigforward = self.sigforward.get_menu().get_active().get_data("id")
            self.prefs.confirmsend = self.confirmsend.get_active()
            self.prefs.filter_start = self.filter_start.get_active()
            self.prefs.fillwidth = int(self.fillwidth.get_value())
	    self.prefs.sub_font = self.sub_fontpicker.get_font_name()
	    self.prefs.fld_font = self.fld_fontpicker.get_font_name()
	    self.prefs.msg_font = self.msg_fontpicker.get_font_name()
	    self.prefs.compose_font = self.compose_fontpicker.get_font_name()
            if self.externaled_support:
                self.prefs.externaled_font = self.externaled_fontpicker.get_font_name()
            self.prefs.external_cmd = self.externalentry.gtk_entry().get_text()
            self.prefs.invoke_at_startup = self.invokeentry.get_active()
            self.prefs.gtkhtml = self.gtkhtml.get_active()

	    #editor prefs
            if self.externaled_support:
                self.prefs.usebuiltined = self.usebuiltined.get_active()
                self.prefs.externaledentry = self.externaledentry.get_text()
                self.prefs.editorhints = self.editorhints.get_menu().get_active().get_data("id")

            # Ensure only one of mailserver or smtp is set
            if self.prefs.usemailserver:
                self.prefs.usesendmail = 0
            if self.prefs.usesendmail:
                self.prefs.usemailserver = 0

            # Check that the username and email address is entered
            if len(self.prefs.accounts) == 0:
                w = GnomeErrorDialog(err1)
                w.set_parent(self.win)
                w.show()
                return

            # Check if the folder directory exists
            try:
                os.stat(self.prefs.folders)
            except os.error:
                # Need to create the directory
                try:
                    os.mkdir(self.prefs.folders)
                except os.error:
                    # Could not create directory
                    w = GnomeErrorDialog(err3 % self.prefs.folders)
                    w.set_parent(self.win)
                    w.show()
                    return
                
            # Find all folders in the mail directory
            try:
                flds = map( lambda x, y=split: y(x)[1],
                            glob.glob(self.prefs.folders+'/*') )
            except IndexError:
                flds = []
                
            # Ensure that the default folders are present
            for f in self.prefs.default_folders:
                if f not in flds:
                    # Create default folder file
                    open(self.prefs.folders+'/'+f, 'a').close()
                    # Create the index file
                    folderops.create_folder_index(self.prefs.folders+"/"+f)

            # Save configuration to disk
            self.prefs.save()

            # Finished
            self.win.destroy()

        elif no == 1:
            # Just bail out without doing any modifications
            self.win.destroy()
        else:
            print "preferences -- got unknown button callback event"


    ##
    ## Method init_notebook (self)
    ##
    ##    Create the notbook widget.
    ##
    ##
    def init_notebook(self):
        notebook = GtkNotebook()
        notebook.set_tab_pos(POS_TOP)

        frame = GtkFrame('Accounts')
        frame.set_border_width(10)
        frame.set_usize(400, 320)
        frame.show()
        label = GtkLabel('Accounts')
        notebook.append_page(frame, label)
        self.init_account(frame)

        frame = GtkFrame('Incoming')
        frame.set_border_width(10)
        frame.set_usize(400, 320)
        frame.show()
        label = GtkLabel('Incoming')
        notebook.append_page(frame, label)
        self.init_incoming(frame)

        frame = GtkFrame('Outgoing')
        frame.set_border_width(10)
        frame.set_usize(400, 320)
        frame.show()
        label = GtkLabel('Outgoing')
        notebook.append_page(frame, label)
        self.init_outgoing(frame)
    
        if self.externaled_support:
            frame = GtkFrame('Editor')
            frame.set_border_width(10)
            frame.set_usize(400, 320)
            frame.show()
            label = GtkLabel('Editor')
            notebook.append_page(frame, label)
            self.init_editor(frame)

        frame = GtkFrame('Mail')
        frame.set_border_width(10)
        frame.set_usize(400, 320)
        frame.show()
        label = GtkLabel('Mail')
        notebook.append_page(frame, label)
        self.init_messages(frame)
        
        frame = GtkFrame('Misc')
        frame.set_border_width(10)
        frame.set_usize(400, 320)
        frame.show()
        label = GtkLabel('Misc')
        notebook.append_page(frame, label)
        self.init_fonts(frame)
        
        self.vbox.pack_start(notebook)
        notebook.show()


    ##
    ## Method *acc* (self)
    ##
    ##    Methods for account management
    ##
    ##
    def update_acc(self):
        self.acc.clear()
        e = self.entry.keys()
        if DEF_ACC in e:
            e.remove(DEF_ACC)
        e.sort()
        for name in e:
            self.acc.append( (name,) )
        acc = self.prefs.defacc
        if acc and len(e) > 0:
            if acc in e:
                row = e.index(acc)
                self.acc.set_background(row, GdkColor(25535,25535,32535))
            else:
                self.prefs.defacc = ''


    def acc_edit_cb(self, button, no):
        w = self.dialogs[button]
        accname = w[5]
        if no == 0:
            del self.entry[accname]
            self.entry[w[0].get_text()] = [
                w[1].get_text(),
                w[2].get_text(),
                w[4].gtk_entry().get_text(),
                w[3].get_text(),
                ]
            self.update_acc()
        elif no == 1:
            pass
        del self.dialogs[button]
        button.destroy()
            

    def acc_select(self, list, r, c, ev):
        if hasattr(ev, 'type'):
            # Check for double clicks on the list item
            if ev.type == 5: 
                name = list.get_text(r,c)
                v = GnomeDialog('Modify Account %s' % name, 'Ok', 'Cancel')
                v.set_parent(self.win)
                v.connect('clicked', self.acc_edit_cb)        
                v.show()
                t, self.dialogs[v] = self.acc_view(name)
                v.vbox.pack_start(t)


    def acc_new(self, button):
        v = GnomeDialog('New Account', 'Ok', 'Cancel')
        v.set_parent(self.win)
        v.connect('clicked', self.acc_new_cb)        
        v.show()
        import pwd
        pwdline = pwd.getpwuid(os.getuid())
        dummy = [pwdline[4],
                 '%s@' % pwdline[0],
                 '%s/.signature' % pwdline[5],
                 '%s@' % pwdline[0]
                 ]
        self.entry[DEF_ACC] = dummy
        t, self.dialogs[v] = self.acc_view(DEF_ACC)
        v.vbox.pack_start(t)
 

    def acc_new_cb(self, button, no):
        w = self.dialogs[button]
        if no == 0:
            self.entry[w[0].get_text()] = [
                w[1].get_text(),
                w[2].get_text(),
                w[4].gtk_entry().get_text(),
                w[3].get_text(),
                ]
            self.update_acc()
        del self.dialogs[button]
        button.destroy()


    def acc_remove(self, button):
        if self.acc.selection == []:
            return
        row = self.acc.selection[0]
        account = self.acc.get_text(row, 0)
        if account == self.prefs.defacc:
            self.prefs.defacc = ''
        del self.entry[account]
        self.update_acc()
        

    def acc_view(self, accname):
        name, email, sigfile, reply = self.entry[accname]
        t = GtkTable(11,1,0)
        t.show()
	la = GtkLabel("Account name:")
	la.show()
	accentry = GtkEntry()
        accentry.show()
        accentry.set_text(accname)
	ln = GtkLabel("User name:")
	ln.show()
	nameentry = GtkEntry()
        nameentry.show()
        if name != None:
            nameentry.set_text(name)
	le = GtkLabel("Email address:")
	le.show()
	mailentry = GtkEntry()
        mailentry.show()
        if email != None:
            mailentry.set_text(email)
	ls = GtkLabel("Signature file:")
	ls.show()
	sigentry = GnomeFileEntry()
        sigentry.gnome_entry().set_history_id('signature')
        sigentry.gnome_entry().load_history()
        sigentry.show()
        if sigfile != None:
            sigentry.gtk_entry().set_text(sigfile)
	lr = GtkLabel("Reply-to address:")
	lr.show()
	replyentry = GtkEntry()
        replyentry.show()
        if reply != None:
            replyentry.set_text(reply)
        t.attach(la, 0, 1, 0, 1, yoptions=0, ypadding=3)
        t.attach(accentry, 0, 1, 1, 2, xpadding=40, yoptions=0,
                 ypadding=3)
        t.attach(ln, 0, 1, 2, 3, yoptions=0, ypadding=3)
        t.attach(nameentry, 0, 1, 3, 4, xpadding=40, yoptions=0,
                 ypadding=3)
        t.attach(le, 0, 1, 4, 5, yoptions=0, ypadding=3)
        t.attach(mailentry, 0, 1, 5, 6, xpadding=40, yoptions=0,
                 ypadding=3)
        t.attach(lr, 0, 1, 6, 7, yoptions=0, ypadding=3)
        t.attach(replyentry, 0, 1, 7, 8, xpadding=40, yoptions=0,
                 ypadding=3)
        t.attach(ls, 0, 1, 8, 9, yoptions=0, ypadding=3)
        t.attach(sigentry, 0, 1, 10, 11, xpadding=40, yoptions=0,
                 ypadding=3)
        return t, (accentry, nameentry, mailentry, replyentry, sigentry,
                   accname)


    def set_as_default(self, button):
        if self.acc.selection == []:
            return
        row = self.acc.selection[0]
        account = self.acc.get_text(row, 0)
        self.prefs.defacc = account
        self.update_acc()
        

    ## Create the account notebook
    def init_account(self, frame):
        t = GtkTable(8,1,0)
        t.show()
        acc = GtkCList(1, ['Name'])
        acc.connect("select_row", self.acc_select)
        # Widget attributes
        acc.set_selection_mode(SELECTION_SINGLE)
        acc.set_column_width(0, 150)
        acc.set_column_width(1, 150)
        acc.set_border_width(2)
        acc.set_usize(0, 250)
        # Add scrollbars
        swin = GtkScrolledWindow()
        swin.set_policy(POLICY_AUTOMATIC, POLICY_AUTOMATIC)
        swin.add(acc)
        swin.show()
        acc.show()
        t.attach(swin, 0, 3, 0, 1, yoptions=0)
        # 'Default' button
        b = GtkButton('Set as default')
        b.show()
        b.connect('clicked', self.set_as_default)
        t.attach(b, 0, 1, 1, 2, yoptions=0, ypadding=5, xpadding=5)
        # 'Delete' button
        b = GtkButton('Remove')
        b.show()
        b.connect('clicked', self.acc_remove)
        t.attach(b, 1, 2, 1, 2, yoptions=0, ypadding=5, xpadding=5)
        # 'New...' button
        b = GtkButton('New...')
        b.show()
        b.connect('clicked', self.acc_new)
        t.attach(b, 2, 3, 1, 2, yoptions=0, ypadding=5, xpadding=5)

        frame.add(t)

        # Add entries to the list view
        self.acc = acc
        self.update_acc()


    ## Create the 'Outgoing' notebook
    def init_outgoing(self, frame):
        t = GtkTable(8,1,0)
        t.show()
	self.usemailserver = GtkRadioButton(None, "Send using mail server:")
	self.usemailserver.show()
        self.usemailserver.set_active(self.prefs.usemailserver)
	self.serverentry = GtkEntry()
        self.serverentry.show()
        self.serverentry.set_text(self.prefs.serverentry)
        self.usesendmail = GtkRadioButton(self.usemailserver,
                                          "Send using local 'sendmail':")
	self.usesendmail.show()
        self.usesendmail.set_active(self.prefs.usesendmail)
	self.sendmailentry = GnomeFileEntry()
        self.sendmailentry.gnome_entry().set_history_id('sendmail')
        self.sendmailentry.gnome_entry().load_history()
        self.sendmailentry.show()
        self.sendmailentry.gtk_entry().set_text(self.prefs.sendmailentry)
        t.attach(self.usemailserver, 0, 1, 0, 1, yoptions=0, ypadding=3, xpadding=10)
        t.attach(self.serverentry, 0, 1, 1, 2, xpadding=10, yoptions=0,
                 ypadding=3)
        t.attach(self.usesendmail, 0, 1, 2, 3, yoptions=0, ypadding=3, xpadding=10)
        t.attach(self.sendmailentry, 0, 1, 3, 4, xpadding=10, yoptions=0,
                 ypadding=3)
        frame.add(t)

    ## Create the 'Editor' notebook
    def init_editor(self, frame):
	from externaleditor import hintlist
        t = GtkTable(8,1,0)
        t.show()
	self.usebuiltined = GtkRadioButton(None, "Use standard editor")
	self.usebuiltined.show()
        self.usebuiltined.set_active(self.prefs.usebuiltined)
        self.useexternaled = GtkRadioButton(self.usebuiltined,
                                          "Use external editor")
	self.useexternaled.show()
        self.useexternaled.set_active( not self.prefs.usebuiltined)
	self.externaledentry = GtkEntry()
        self.externaledentry.show()
	self.externaledentry.set_sensitive( not self.prefs.usebuiltined )
        self.externaledentry.set_text(self.prefs.externaledentry)

	self.usebuiltined.connect('clicked', self.editor_cb, 1 )
	self.useexternaled.connect('clicked', self.editor_cb, 0 )

	
        self.editorhints = GtkOptionMenu()
        self.editorhints.show()
        self.editorhints.set_sensitive( not self.prefs.usebuiltined )
        m = GtkMenu()

	n = 0
        for menu in hintlist:
	    # add the item to the option list
            i = GtkMenuItem(menu[0])
	    i.set_data("id", menu[1])
            i.show()
            m.append(i)

	    # check if this item should be made "active"
	    if self.prefs.editorhints == menu[1]:
		active = n	
	    n = n + 1

	m.set_active(active)
        self.editorhints.set_menu(m)

	b = GtkHBox()
	lc = GtkLabel("External Editor Font: ")
    	lc.show()
        lc.set_alignment(0.0, 0.5)
        b.pack_start(lc, expand=FALSE, fill=TRUE)
	mc = PFontPicker()
	mc.set_mode(FONT_PICKER_MODE_FONT_INFO)
	if self.prefs.externaled_font != None:
		mc.set_font_name(self.prefs.externaled_font)
	mc.show()
	self.externaled_fontpicker = mc
        b.pack_start(mc, expand=FALSE, fill=TRUE)
	b.show()

        t.attach(self.usebuiltined, 0, 1, 0, 1, yoptions=0, ypadding=3, xpadding=10)
        t.attach(self.useexternaled, 0, 1, 1, 2, xpadding=10, yoptions=0,
                 ypadding=3)
        t.attach(self.externaledentry, 0, 1, 2, 3, yoptions=0, ypadding=3, xpadding=10)
        t.attach(self.editorhints, 0, 1, 3, 4, yoptions=0, ypadding=3, xpadding=10)
        t.attach(b, 0, 1, 4, 5, yoptions=0, ypadding=3, xpadding=10)
        frame.add(t)

    def editor_cb( self, widget=None, usebuiltin=1 ):
	self.externaledentry.set_sensitive( not usebuiltin )
	self.editorhints.set_sensitive( not usebuiltin )
	self.externaled_fontpicker.set_sensitive( not usebuiltin )


    ## Create the 'Incoming' notebook
    def init_incoming(self, frame):
        t = GtkTable(8,1,0)
        t.show()

	lf = GtkLabel("Incoming mail file:")
	lf.show()
        lf.set_alignment(0.0, 0.5)
	self.spoolentry = GnomeFileEntry()
        self.spoolentry.show()
        self.spoolentry.gnome_entry().set_history_id('mailspool')
        self.spoolentry.gnome_entry().load_history()
        if self.prefs.spoolfile != None:
            self.spoolentry.gtk_entry().set_text(self.prefs.spoolfile)

	lm = GtkLabel("Mail folder directory:")
	lm.show()
        lm.set_alignment(0.0, 0.5)
	self.direntry = GnomeFileEntry()
        self.direntry.show()
        self.direntry.gnome_entry().set_history_id('folderdir')
        self.direntry.gnome_entry().load_history()
        if self.prefs.folders != None:
            self.direntry.gtk_entry().set_text(self.prefs.folders)

        lec = GtkLabel("External command for mail fetching:")
        lec.show()
        lec.set_alignment(0.0, 0.5)
	self.externalentry = GnomeFileEntry()
        self.externalentry.show()
        self.externalentry.gnome_entry().set_history_id('external')
        self.externalentry.gnome_entry().load_history()
        if self.prefs.external_cmd:
            self.externalentry.gtk_entry().set_text(self.prefs.external_cmd)

        self.invokeentry = GtkCheckButton("Invoke external command at startup")
	self.invokeentry.show()
        self.invokeentry.set_active(self.prefs.invoke_at_startup)

        t.attach(lf, 0, 1, 0, 1, yoptions=0, ypadding=3, xpadding=10)
        t.attach(self.spoolentry, 0, 1, 1, 2, xpadding=10, yoptions=0,
                 ypadding=3)
        t.attach(lm, 0, 1, 3, 4, yoptions=0, ypadding=3, xpadding=10)
        t.attach(self.direntry, 0, 1, 4, 5, xpadding=10, yoptions=0,
                 ypadding=3)
        t.attach(lec, 0, 1, 5, 6, yoptions=0, ypadding=3, xpadding=10)
        t.attach(self.externalentry, 0, 1, 6, 7, xpadding=10, yoptions=0,
                 ypadding=3)
        t.attach(self.invokeentry, 0, 1, 7, 8, xpadding=10, yoptions=0,
                 ypadding=3)
        frame.add(t)


    # Create the 'Fonts:' notebook
    def init_fonts(self, frame):
        t = GtkTable(8,1,0)
        t.show()
    
	lf = GtkLabel("Folder Tree:")
	lf.show()
        lf.set_alignment(0.0, 0.5)
	fp = PFontPicker()
	fp.set_mode(FONT_PICKER_MODE_FONT_INFO)
	if self.prefs.fld_font != None:
		fp.set_font_name(self.prefs.fld_font)
	fp.show()
	self.fld_fontpicker = fp
	
	ls = GtkLabel("Message Headers:")
	ls.show()
        ls.set_alignment(0.0, 0.5)
	sp = PFontPicker()
	sp.set_mode(FONT_PICKER_MODE_FONT_INFO)
	if self.prefs.sub_font != None:
		sp.set_font_name(self.prefs.sub_font)
	sp.show()
	self.sub_fontpicker = sp
	
	lm = GtkLabel("Message Body:")
    	lm.show()
        lm.set_alignment(0.0, 0.5)
	mp = PFontPicker()
	mp.set_mode(FONT_PICKER_MODE_FONT_INFO)
	if self.prefs.msg_font != None:
		mp.set_font_name(self.prefs.msg_font)
	mp.show()
	self.msg_fontpicker = mp

	lc = GtkLabel("Compose Body:")
    	lc.show()
        lc.set_alignment(0.0, 0.5)
	mc = PFontPicker()
	mc.set_mode(FONT_PICKER_MODE_FONT_INFO)
	if self.prefs.compose_font != None:
		mc.set_font_name(self.prefs.compose_font)
	mc.show()
	self.compose_fontpicker = mc

        self.gtkhtml = GtkCheckButton("If available, use GtkHTML for message viewing")
	self.gtkhtml.show()
        self.gtkhtml.set_active(self.prefs.gtkhtml)

        v = GtkHBox()
        v.show()
        fillval = self.prefs.fillwidth
        fillwidth_label = GtkLabel("Set fill-width for paragraphs ")
        fillwidth_label.show()
        self.fillwidth = GtkSpinButton(GtkAdjustment(fillval,10,130,1,10,0), 0, 0)
        self.fillwidth.show()
        v.pack_start(fillwidth_label, expand=FALSE, fill=TRUE)
        v.pack_start(self.fillwidth, expand=FALSE, fill=FALSE)

	t.attach(lf, 0, 1, 0, 1, yoptions=0, ypadding=3, xpadding=10)
	t.attach(fp, 1, 2, 0, 1, xpadding=20, yoptions=0, ypadding=3)
	t.attach(ls, 0, 1, 2, 3, yoptions=0, ypadding=3, xpadding=10)
	t.attach(sp, 1, 2, 2, 3, xpadding=20, yoptions=0, ypadding=3)
	t.attach(lm, 0, 1, 4, 5, yoptions=0, ypadding=3, xpadding=10)
	t.attach(mp, 1, 2, 4, 5, xpadding=20, yoptions=0, ypadding=3)
	t.attach(lc, 0, 1, 6, 7, yoptions=0, ypadding=3, xpadding=10)
	t.attach(mc, 1, 2, 6, 7, xpadding=20, yoptions=0, ypadding=3)
        t.attach(self.gtkhtml, 0, 2, 7, 8, xpadding=10, yoptions=0, ypadding=3)
        t.attach(v, 0, 2, 8, 9, xpadding=10, yoptions=0, ypadding=3)
    	frame.add(t)


    ## Create the 'Messages' notebook
    def init_messages(self, frame):
        t = GtkTable(6,2,0)
        t.show()

        self.notify = GtkCheckButton("Popup notify window when new mail arrives")
	self.notify.show()
        self.notify.set_active(self.prefs.mailnotify)

        self.trash = GtkCheckButton("Empty 'trash' folder on exit")
	self.trash.show()
        self.trash.set_active(self.prefs.trash)

	# create the menus for where to put signatures when replying 
	# and when forwarding
        rb = GtkHBox()
        fb = GtkHBox()
        self.sigreply = GtkOptionMenu()
        self.sigreply.show()
        self.sigreply.set_sensitive( self.prefs.addsig )

        self.sigforward = GtkOptionMenu()
        self.sigforward.show()
        self.sigforward.set_sensitive( self.prefs.addsig )
        rm = GtkMenu()
	fm = GtkMenu()
	n = 0
        ractive = 1
        factive = 1
        s = [ ("Don't use signature", 'none'),
              ("Put signature after cited text", 'after'),
              ("Put signature before cited text", 'before') ]
        for menu in s:
	    # add the item to each option list
            ri = GtkMenuItem(menu[0])
	    ri.set_data("id", menu[1])
            ri.show()
            rm.append(ri)

            fi = GtkMenuItem(menu[0])
	    fi.set_data("id", menu[1])
            fi.show()
            fm.append(fi)

	    # check if this item should be made "active"
	    if self.prefs.sigreply == menu[1]:
		ractive = n	
	    if self.prefs.sigforward == menu[1]:
		factive = n	
	    n = n + 1

	rm.set_active(ractive)
	fm.set_active(factive)

        self.sigreply.set_menu(rm)
        l = GtkLabel(" when replying")
        l.show()
        rb.pack_start(self.sigreply, expand=FALSE, fill=TRUE)
        rb.pack_start(l, expand=FALSE, fill=TRUE)
        rb.show()

        self.sigforward.set_menu(fm)
        l = GtkLabel(" when forwarding")
        l.show()
        fb.pack_start(self.sigforward, expand=FALSE, fill=TRUE)
        fb.pack_start(l, expand=FALSE, fill=TRUE)
        fb.show()

        self.addsig = GtkCheckButton("Automatically add signature in composer")
	self.addsig.show()
	self.addsig.connect('clicked', self.addsig_cb )
        self.addsig.set_active(self.prefs.addsig)

        self.expand = GtkCheckButton("Confirm address list name expansions")
	self.expand.show()
        self.expand.set_active(self.prefs.expand)

        self.confirmsend = GtkCheckButton("Popup notify window when mail has been successfully sent")
	self.confirmsend.show()
        self.confirmsend.set_active(self.prefs.confirmsend)

        self.filter_start = GtkCheckButton("When getting new mail, only run filters on new mail")
	self.filter_start.show()
        self.filter_start.set_active(self.prefs.filter_start)

        self.gtkhtml = GtkCheckButton("If available, use GtkHTML for message viewing")
	self.gtkhtml.show()
        self.gtkhtml.set_active(self.prefs.gtkhtml)

        v = GtkHBox()
        v.show()
        fillval = self.prefs.fillwidth
        fillwidth_label = GtkLabel("Set fill-width for paragraphs ")
        fillwidth_label.show()
        self.fillwidth = GtkSpinButton(GtkAdjustment(fillval,10,130,1,10,0), 0, 0)
        self.fillwidth.show()
        v.pack_start(fillwidth_label, expand=FALSE, fill=TRUE)
        v.pack_start(self.fillwidth, expand=FALSE, fill=FALSE)

        t.attach(self.notify, 0, 1, 0, 1, xpadding=10, yoptions=0, ypadding=3)
        t.attach(self.trash, 0, 1, 1, 2, xpadding=10, yoptions=0, ypadding=3)
        t.attach(self.addsig, 0, 1, 2, 3, xpadding=10, yoptions=0, ypadding=3)
        t.attach(rb, 0, 1, 3, 4, xpadding=10, yoptions=0, ypadding=3)
        t.attach(fb, 0, 1, 4, 5, xpadding=10, yoptions=0, ypadding=3)
        t.attach(self.expand, 0, 1, 5, 6, xpadding=10, yoptions=0, ypadding=3)
        t.attach(self.confirmsend, 0, 1, 6, 7, xpadding=10, yoptions=0, ypadding=3)
        t.attach(self.filter_start, 0, 1, 7, 8, xpadding=10, yoptions=0, ypadding=3)
        frame.add(t)

    def addsig_cb( self, widget=None ):
	self.sigreply.set_sensitive( self.addsig.get_active() )
	self.sigforward.set_sensitive( self.addsig.get_active() )

    ## Window mainloop
    def mainloop(self):
        mainloop()
