########################################################################
# $Header: /var/local/cvsroot/4Suite/Ft/Xml/Xslt/HtmlWriter.py,v 1.29 2005/02/09 09:14:48 mbrown Exp $
"""
HTML writer for XSLT processor output

Copyright 2005 Fourthought, Inc. (USA).
Detailed license and copyright information: http://4suite.org/COPYRIGHT
Project home, documentation, distributions: http://4suite.org/
"""

from Ft.Xml import EMPTY_NAMESPACE
from Ft.Xml.Lib import HtmlPrinter, HtmlPrettyPrinter
from Ft.Xml.Xslt import XmlWriter

class HtmlWriter(XmlWriter.XmlWriter):
    """
    Takes events such as those generated by an XSLT processor and
    invokes a serializer to produce HTML. Uses XML syntax for
    elements in a non-empty namespace. Instructs the serializer to
    insert a Content-Type 'meta' element in the first 'head' element.
    """

    def _completeLastElementAfterMeta(self):
        XmlWriter.XmlWriter._completeLastElement(self)
        return

    def _completeLastElement(self):
        # XmlWriter clears self._elementName before returning
        if self._elementName and self._elementUri == EMPTY_NAMESPACE:
            in_head_tag = (self._elementName.lower() == u'head')
        else:
            in_head_tag = False

        XmlWriter.XmlWriter._completeLastElement(self)

        if in_head_tag:
            # Output the META tag
            content = u'%s; charset=%s' % (self._outputParams.mediaType,
                                           self._outputParams.encoding)
            attrs = {u'http-equiv' : u'Content-Type',
                     u'content' : content,
                     }
            self._printer.startElement(None, u'meta', {}, attrs)
            self._printer.endElement(None, u'meta')
            self._completeLastElement = self._completeLastElementAfterMeta

        return

    def startDocument(self):
        self._outputParams.setDefault('version', '4.0')
        self._outputParams.setDefault('encoding', 'iso-8859-1')
        self._outputParams.setDefault('indent', 1)
        self._outputParams.setDefault('mediaType', 'text/html')

        encoding = self._outputParams.encoding.encode('ascii')
        version = self._outputParams.version.encode('ascii')

        if self._outputParams.indent:
            printer = HtmlPrettyPrinter.HtmlPrettyPrinter
        else:
            printer = HtmlPrinter.HtmlPrinter
        self._printer = printer(self._stream, encoding)

        self._printer.startDocument(version)
        return
