## $Id: html.py,v 1.8 2001/09/26 14:29:09 kjetilja Exp $

## System modules
from gtk import *
from gnome.ui import *
import gnome.mime
from gtkhtml import *
import os, string, re

## Error messages from the GUI
err1 = "No external viewer defined for text/html"

## Grab URLs and make them clickable for regular mails
tags = re.compile('(<URL:(http://[\w\.\S]+)>)|(http://[\w\.\S]+)', re.I|re.M)

## Grab cited lines and transform them to make them easier to read
cites = re.compile('^>(.*)$', re.M)


##
##
## HTML message rendering window class
##
##
class HtmlWindow(GtkHTML):


    def __init__(self, msgwin):
        GtkHTML.__init__(self)
        self.show()
        self.connect('link_clicked', self.load_uri)
        self.connect('on_url', self.anchor_track)
        self.handle = None
        self.msgwin = msgwin
        self.load_empty()


    def insert(self, body, type):
        def uri(match):
            m1, m2 = match.group(2), match.group(3)
            m = m1 or m2
            return "<a href='%s'>%s</a>" % (m, m)

        def cite(match):
            # This should probably be configurable later on
            return "<font color=darkred>>%s</font>" % match.group(1)

        if not self.handle:
            self.handle = self.begin()
        else:
            self.write(self.handle, '<hr>')
        body = cites.sub(cite, body)
        if type != 'text/html':
            body = tags.sub(uri, body)
            body = '<pre>%s</pre>' % body
        self.write(self.handle, body)


    def end_insert(self):
        if self.handle != None:
            self.end(self.handle, HTML_STREAM_OK)
            self.handle = None


    def anchor_track(self, html, uri):
        if uri != None:
            self.msgwin.fld.appbar.set_status(uri)
        else:
            self.msgwin.fld.appbar.set_status('')


    def load_uri(self, html, url):
        gtypekeys = gnome.mime.get_keys('text/html')
        if 'open' in gtypekeys:
            prog = gnome.mime.program('text/html')
            if not prog:
                w = GnomeErrorDialog(err1)
                w.show()
                return
        else:
            w = GnomeErrorDialog(err1)
            w.show()
            return

        prog = string.split(prog, ' ')[0]
        cmd = prog + " '" + url + "' 2>/dev/null &"
        os.system(cmd)
