# -*- coding: utf-8 -*-
#
# Copyright (C) 2004-2007 Edgewall Software
# Copyright (C) 2004 Daniel Lundin <daniel@edgewall.com>
# Copyright (C) 2005-2006 Christopher Lenz <cmlenz@gmx.de>
# Copyright (C) 2006-2007 Christian Boos <cboos@neuf.fr>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
#
# Author: Daniel Lundin <daniel@edgewall.com>
#         Christopher Lenz <cmlenz@gmx.de>
#         Christian Boos <cboos@neuf.fr>

"""
----
NOTE: for plugin developers

 The Mimeview API is quite complex and many things there are currently
 a bit difficult to work with (e.g. what an actual `content` might be,
 see last paragraph of this docstring).

 So this area is mainly in a ''work in progress'' state, which will
 be improved upon in the near future
 (see http://trac.edgewall.org/ticket/3332).

 In particular, if you are interested in writing IContentConverter
 and IHTMLPreviewRenderer components, note that those interfaces
 will be merged into a new style IContentConverter.
 Feel free to contribute remarks and suggestions for improvements
 to the corresponding ticket (#3332).
----

The `trac.mimeview` module centralize the intelligence related to
file metadata, principally concerning the `type` (MIME type) of the content
and, if relevant, concerning the text encoding (charset) used by the content.

There are primarily two approaches for getting the MIME type of a given file:
 * taking advantage of existing conventions for the file name
 * examining the file content and applying various heuristics

The module also knows how to convert the file content from one type
to another type.

In some cases, only the `url` pointing to the file's content is actually
needed, that's why we avoid to read the file's content when it's not needed.

The actual `content` to be converted might be a `unicode` object,
but it can also be the raw byte string (`str`) object, or simply
an object that can be `read()`.
"""

import re
from StringIO import StringIO

from genshi import Markup, Stream
from genshi.core import TEXT, START, END, START_NS, END_NS
from genshi.builder import Fragment, tag
from genshi.input import HTMLParser

from trac.config import IntOption, ListOption, Option
from trac.core import *
from trac.util import reversed, sorted, Ranges
from trac.util.text import to_utf8, to_unicode


__all__ = ['get_mimetype', 'is_binary', 'detect_unicode', 'Mimeview',
           'content_to_unicode', 'RenderingContext']


# Some common MIME types and their associated keywords and/or file extensions

KNOWN_MIME_TYPES = {
    'application/pdf':        ['pdf'],
    'application/postscript': ['ps'],
    'application/rtf':        ['rtf'],
    'application/x-sh':       ['sh'],
    'application/x-csh':      ['csh'],
    'application/x-troff':    ['nroff', 'roff', 'troff'],
    'application/x-yaml':     ['yml', 'yaml'],
    
    'application/rss+xml':    ['rss'],
    'application/xsl+xml':    ['xsl'],
    'application/xslt+xml':   ['xslt'],
    
    'image/x-icon':           ['ico'],
    'image/svg+xml':          ['svg'],
    
    'model/vrml':             ['vrml', 'wrl'],
    
    'text/css':               ['css'],
    'text/html':              ['html'],
    'text/plain':             ['txt', 'TXT', 'text', 'README', 'INSTALL',
                               'AUTHORS', 'COPYING', 'ChangeLog', 'RELEASE'],
    'text/xml':               ['xml'],
    'text/x-csrc':            ['c', 'xs'],
    'text/x-chdr':            ['h'],
    'text/x-c++src':          ['cc', 'CC', 'cpp', 'C'],
    'text/x-c++hdr':          ['hh', 'HH', 'hpp', 'H'],
    'text/x-csharp':          ['cs'],
    'text/x-diff':            ['diff', 'patch'],
    'text/x-eiffel':          ['e'],
    'text/x-elisp':           ['el'],
    'text/x-fortran':         ['f'],
    'text/x-haskell':         ['hs'],
    'text/x-javascript':      ['js'],
    'text/x-objc':            ['m', 'mm'],
    'text/x-ocaml':           ['ml', 'mli'],
    'text/x-makefile':        ['make', 'mk',
                               'Makefile', 'makefile', 'GNUMakefile'],
    'text/x-pascal':          ['pas'],
    'text/x-perl':            ['pl', 'pm', 'PL', 'perl'],
    'text/x-php':             ['php', 'php3', 'php4'],
    'text/x-python':          ['py', 'python'],
    'text/x-pyrex':           ['pyx'],
    'text/x-ruby':            ['rb', 'ruby'],
    'text/x-scheme':          ['scm'],
    'text/x-textile':         ['txtl', 'textile'],
    'text/x-vba':             ['vb', 'vba', 'bas'],
    'text/x-verilog':         ['v', 'verilog'],
    'text/x-vhdl':            ['vhd'],
}

# extend the above with simple (text/x-<something>: <something>) mappings

for x in ['ada', 'asm', 'asp', 'awk', 'idl', 'inf', 'java', 'ksh', 'lua',
          'm4', 'mail', 'psp', 'rfc', 'rst', 'sql', 'tcl', 'tex', 'zsh']:
    KNOWN_MIME_TYPES.setdefault('text/x-%s' % x, []).append(x)


# Default mapping from keywords/extensions to known MIME types:

MIME_MAP = {}
for t, exts in KNOWN_MIME_TYPES.items():
    MIME_MAP[t] = t
    for e in exts:
        MIME_MAP[e] = t

# Simple builtin autodetection from the content using a regexp
MODE_RE = re.compile(
    r"#!.+?env (\w+)|"                       # look for shebang with env
    r"#!(?:[/\w.-_]+/)?(\w+)|"               # look for regular shebang
    r"-\*-\s*(?:mode:\s*)?([\w+-]+)\s*-\*-|" # look for Emacs' -*- mode -*-
    r"vim:.*?(?:syntax|filetype|ft)=(\w+)"   # look for VIM's syntax=<n>
    )

def get_mimetype(filename, content=None, mime_map=MIME_MAP):
    """Guess the most probable MIME type of a file with the given name.

    `filename` is either a filename (the lookup will then use the suffix)
    or some arbitrary keyword.
    
    `content` is either a `str` or an `unicode` string.
    """
    suffix = filename.split('.')[-1]
    if suffix in mime_map:
        # 1) mimetype from the suffix, using the `mime_map`
        return mime_map[suffix]
    else:
        mimetype = None
        try:
            import mimetypes
            # 2) mimetype from the suffix, using the `mimetypes` module
            mimetype = mimetypes.guess_type(filename)[0]
        except:
            pass
        if not mimetype and content:
            match = re.search(MODE_RE, content[:1000] + content[-1000:])
            if match:
                mode = match.group(1) or match.group(2) or match.group(4) or \
                    match.group(3).lower()
                if mode in mime_map:
                    # 3) mimetype from the content, using the `MODE_RE`
                    return mime_map[mode]
            else:
                if is_binary(content):
                    # 4) mimetype from the content, using`is_binary`
                    return 'application/octet-stream'
        return mimetype

def is_binary(data):
    """Detect binary content by checking the first thousand bytes for zeroes.

    Operate on either `str` or `unicode` strings.
    """
    if isinstance(data, str) and detect_unicode(data):
        return False
    return '\0' in data[:1000]

def detect_unicode(data):
    """Detect different unicode charsets by looking for BOMs (Byte Order Marks).

    Operate obviously only on `str` objects.
    """
    if data.startswith('\xff\xfe'):
        return 'utf-16-le'
    elif data.startswith('\xfe\xff'):
        return 'utf-16-be'
    elif data.startswith('\xef\xbb\xbf'):
        return 'utf-8'
    else:
        return None

def content_to_unicode(env, content, mimetype):
    """Retrieve an `unicode` object from a `content` to be previewed"""
    mimeview = Mimeview(env)
    if hasattr(content, 'read'):
        content = content.read(mimeview.max_preview_size)
    return mimeview.to_unicode(content, mimetype)


class RenderingContext(object):
    """Rendering contexts.

    This specifies ''how'' a rendering should be done, with various
    options that might be relevant to some or all the renderers.

    A context stores the `href` used as a base for building URLs.
    If not given, this reverts to the value of `env.abs_href`.
    
    A resource can also be associated to a rendering context, and that resource
    will be used as the base content when rendering relative TracLinks.

    Another aspect related to the access context consists of the scope or
    context trail by which the information belonging to a context is
    presented. It is quite usual that contexts are embedded in other
    contexts. This can be known by querying the `parent` context, which
    is automatically set when creating a subcontext from another context. XXX

    For example, when rendering a ticket description from within a
    Custom Query rendered by the TicketQuery macro inside a wiki page,
    the context ''path'' will be:

    context.resource.(realm, id) = ('ticket', '12')
    context.parent.resource.(realm, id) = ('wiki', 'CurrentStatus')

    Finally, the context could also know about the expected output MIME type
    which should be used to present the information to the user (TODO)
    """

    def __init__(self, req, resource, parent=None, href=None, **kwargs):
        self.req = req
        self.resource = resource or req.perm.toplevel()
        self.env = self.resource.env
        self.perm = self.resource.perm
        self.parent = parent
        self.href = href or self.env.abs_href
        self.properties = kwargs

    def __repr__(self):
        path = []
        context = self
        while context:
            if context.resource.realm: # skip toplevel resource
                path.append(unicode(context.resource))
            context = context.parent
        return '<RenderingContext %s>' % (' - '.join(reversed(path)))

    def __call__(self, resource, href=None, **kwargs):
        """Return a sub-`RenderingContext`.

        'href' can be modified on the fly, which is usefull to e.g. turn URL
        generation to absolute mode.

        'resource' can be modified this way as well.
        Any remaining keyword argument will be treated as a new property.
        """
        return RenderingContext(self.req, resource, self, href or self.href,
                                **kwargs)
    
    def __contains__(self, resource):
        """Check whether a given resource is in the rendering path.

        This is useful for avoiding to render resources recursively.
        """
        context = self
        while context:
            if context.resource == resource:
                return True
            context = context.parent


class IHTMLPreviewRenderer(Interface):
    """Extension point interface for components that add HTML renderers of
    specific content types to the `Mimeview` component.

    ----
    This interface will be merged with IContentConverter, as conversion
    to text/html will be simply a particular type of content conversion.

    However, note that the IHTMLPreviewRenderer will still be supported
    for a while through an adapter, whereas the IContentConverter interface
    itself will be changed.

    So if all you want to do is convert to HTML and don't feel like
    following the API changes, rather you should rather implement this
    interface for the time being.
    ---
    """

    # implementing classes should set this property to True if they
    # support text content where Trac should expand tabs into spaces
    expand_tabs = False

    # indicate whether the output of this renderer is source code that can
    # be decorated with annotations
    returns_source = False

    def get_quality_ratio(mimetype):
        """Return the level of support this renderer provides for the `content`
        of the specified MIME type. The return value must be a number between
        0 and 9, where 0 means no support and 9 means "perfect" support.
        """

    def render(context, mimetype, content, filename=None, url=None):
        """Render an XHTML preview of the raw `content` in context.

        `context` is a `RenderingContext`.

        The `content` might be:
         * a `str` object
         * an `unicode` string
         * any object with a `read` method, returning one of the above

        It is assumed that the content will correspond to the given `mimetype`.

        Besides the `content` value, the same content may eventually
        be available through the `filename` or `url` parameters.
        This is useful for renderers that embed objects, using <object> or
        <img> instead of including the content inline.
        
        Can return the generated XHTML text as a single string or as an
        iterable that yields strings. In the latter case, the list will
        be considered to correspond to lines of text in the original content.
        """


class IHTMLPreviewAnnotator(Interface):
    """Extension point interface for components that can annotate an XHTML
    representation of file contents with additional information."""

    def get_annotation_type():
        """Return a (type, label, description) tuple
        that defines the type of annotation and provides human readable names.
        The `type` element should be unique to the annotator.
        The `label` element is used as column heading for the table,
        while `description` is used as a display name to let the user
        toggle the appearance of the annotation type.
        """
        
    def get_annotation_data(context):
        """Return some metadata to be used by the `annotate_row` method below.

        This will be called only once, before lines are processed.
        If this raises an error, that annotator won't be used.
        """

    def annotate_row(context, row, number, line, data):
        """Return the XHTML markup for the table cell that contains the
        annotation data.

        `context` is the `RenderingContext` corresponding to the content being
        annotated,
        `row` is the tr Element being built, `number` is the line number being
        processed and `line` is the line's actual content.
        `annotations` is whatever additional data the `get_annotation_data`
        method decided to provide.
        """


class IContentConverter(Interface):
    """An extension point interface for generic MIME based content
    conversion.

    ----
    NOTE: This api will likely change in the future, e.g.:

    def get_supported_conversions(input): 
        '''Tells whether this converter can handle this `input` type.

        Return an iterable of `Conversion` objects, each describing
        how the conversion should be done and what will be the output type.
        '''

    def convert_content(context, conversion, content): 
        '''Convert the given `AbstractContent` as specified by `Conversion`.

        The conversion takes place in the given formatting `context`.
        A `context` provides at least a `req` property.
        If no other specific context object is available, a
        `ToplevelContext` can be used to wrap the `req` instance.
        
        Return the converted content, which ''must'' be a `MimeContent` object.
        '''
    ----
    """

    def get_supported_conversions():
        """Return an iterable of tuples in the form (key, name, extension,
        in_mimetype, out_mimetype, quality) representing the MIME conversions
        supported and
        the quality ratio of the conversion in the range 0 to 9, where 0 means
        no support and 9 means "perfect" support. eg. ('latex', 'LaTeX', 'tex',
        'text/x-trac-wiki', 'text/plain', 8)"""

    def convert_content(req, mimetype, content, key):
        """Convert the given content from mimetype to the output MIME type
        represented by key. Returns a tuple in the form (content,
        output_mime_type) or None if conversion is not possible."""


class Mimeview(Component):
    """A generic class to prettify data, typically source code."""

    renderers = ExtensionPoint(IHTMLPreviewRenderer)
    annotators = ExtensionPoint(IHTMLPreviewAnnotator)
    converters = ExtensionPoint(IContentConverter)

    default_charset = Option('trac', 'default_charset', 'iso-8859-15',
        """Charset to be used when in doubt.""")

    tab_width = IntOption('mimeviewer', 'tab_width', 8,
        """Displayed tab width in file preview (''since 0.9'').""")

    max_preview_size = IntOption('mimeviewer', 'max_preview_size', 262144,
        """Maximum file size for HTML preview. (''since 0.9'').""")

    mime_map = ListOption('mimeviewer', 'mime_map',
        'text/x-dylan:dylan,text/x-idl:ice,text/x-ada:ads:adb',
        doc="""List of additional MIME types and keyword mappings.
        Mappings are comma-separated, and for each MIME type,
        there's a colon (":") separated list of associated keywords
        or file extensions. (''since 0.10'').""")

    def __init__(self):
        self._mime_map = None

    # Public API

    def get_supported_conversions(self, mimetype):
        """Return a list of target MIME types in same form as
        `IContentConverter.get_supported_conversions()`, but with the converter
        component appended. Output is ordered from best to worst quality."""
        converters = []
        for converter in self.converters:
            for k, n, e, im, om, q in converter.get_supported_conversions():
                if im == mimetype and q > 0:
                    converters.append((k, n, e, im, om, q, converter))
        converters = sorted(converters, key=lambda i: i[-2], reverse=True)
        return converters

    def convert_content(self, req, mimetype, content, key, filename=None,
                        url=None):
        """Convert the given content to the target MIME type represented by
        `key`, which can be either a MIME type or a key. Returns a tuple of
        (content, output_mime_type, extension)."""
        if not content:
            return ('', 'text/plain;charset=utf-8', '.txt')

        # Ensure we have a MIME type for this content
        full_mimetype = mimetype
        if not full_mimetype:
            if hasattr(content, 'read'):
                content = content.read(self.max_preview_size)
            full_mimetype = self.get_mimetype(filename, content)
        if full_mimetype:
            mimetype = full_mimetype.split(';')[0].strip() # split off charset
        else:
            mimetype = full_mimetype = 'text/plain' # fallback if not binary

        # Choose best converter
        candidates = list(self.get_supported_conversions(mimetype))
        candidates = [c for c in candidates if key in (c[0], c[4])]
        if not candidates:
            raise TracError('No available MIME conversions from %s to %s' %
                            (mimetype, key))

        # First successful conversion wins
        for ck, name, ext, input_mimettype, output_mimetype, quality, \
                converter in candidates:
            output = converter.convert_content(req, mimetype, content, ck)
            if not output:
                continue
            return (output[0], output[1], ext)
        raise TracError('No available MIME conversions from %s to %s' %
                        (mimetype, key))

    def get_annotation_types(self):
        """Generator that returns all available annotation types."""
        for annotator in self.annotators:
            yield annotator.get_annotation_type()

    def render(self, context, mimetype, content, filename=None, url=None,
               annotations=None, force_source=False):
        """Render an XHTML preview of the given `content`.

        `content` is the same as an `IHTMLPreviewRenderer.render`'s
        `content` argument.

        The specified `mimetype` will be used to select the most appropriate
        `IHTMLPreviewRenderer` implementation available for this MIME type.
        If not given, the MIME type will be infered from the filename or the
        content.

        Return a string containing the XHTML text.
        """
        if not content:
            return ''

        # Ensure we have a MIME type for this content
        full_mimetype = mimetype
        if not full_mimetype:
            if hasattr(content, 'read'):
                content = content.read(self.max_preview_size)
            full_mimetype = self.get_mimetype(filename, content)
        if full_mimetype:
            mimetype = full_mimetype.split(';')[0].strip() # split off charset
        else:
            mimetype = full_mimetype = 'text/plain' # fallback if not binary

        # Determine candidate `IHTMLPreviewRenderer`s
        candidates = []
        for renderer in self.renderers:
            qr = renderer.get_quality_ratio(mimetype)
            if qr > 0:
                candidates.append((qr, renderer))
        candidates.sort(lambda x,y: cmp(y[0], x[0]))

        # First candidate which renders successfully wins.
        # Also, we don't want to expand tabs more than once.
        expanded_content = None
        errors = []
        for qr, renderer in candidates:
            if force_source and not getattr(renderer, 'returns_source', False):
                continue # skip non-source renderers in force_source mode
            try:
                ann_names = annotations and ', '.join(annotations) or \
                           'No annotations'
                self.log.debug('Trying to render HTML preview using %s [%s]'
                               % (renderer.__class__.__name__, ann_names))

                # check if we need to perform a tab expansion
                rendered_content = content
                if getattr(renderer, 'expand_tabs', False):
                    if expanded_content is None:
                        content = content_to_unicode(self.env, content,
                                                     full_mimetype)
                        expanded_content = content.expandtabs(self.tab_width)
                    rendered_content = expanded_content

                result = renderer.render(context, full_mimetype,
                                         rendered_content, filename, url)
                if not result:
                    continue

                if not (force_source or getattr(renderer, 'returns_source',
                                                False)):
                    # Direct rendering of content
                    if isinstance(result, basestring):
                        if not isinstance(result, unicode):
                            result = to_unicode(result)
                        return Markup(to_unicode(result))
                    elif isinstance(result, Fragment):
                        return result.generate()
                    else:
                        return result

                # Render content as source code
                if annotations:
                    m = context.req and context.req.args.get('marks') or None
                    return self._render_source(context, result, annotations,
                                               m and Ranges(m))
                else:
                    if isinstance(result, list):
                        result = Markup('\n').join(result)
                    return tag.div(class_='code')(tag.pre(result)).generate()

            except Exception, e:
                self.log.warning('HTML preview using %s failed (%s)' %
                                 (renderer, e), exc_info=True)
                errors.append((renderer, e))
        return errors

    def _render_source(self, context, stream, annotations, marks=None):
        annotators, labels, titles = {}, {}, {}
        for annotator in self.annotators:
            atype, alabel, atitle = annotator.get_annotation_type()
            if atype in annotations:
                labels[atype] = alabel
                titles[atype] = atitle
                annotators[atype] = annotator

        if isinstance(stream, list):
            stream = HTMLParser(StringIO('\n'.join(stream)))
        elif isinstance(stream, unicode):
            text = stream
            def linesplitter():
                for line in text.splitlines(True):
                    yield TEXT, line, (None, -1, -1)
            stream = linesplitter()

        annotator_datas = []
        for a in annotations:
            annotator = annotators[a]
            try:
                data = (annotator, annotator.get_annotation_data(context))
            except TracError, e:
                self.log.warning("Can't use annotator '%s': %s" %
                                 (a, e.message))
                context.req.warning(tag.strong("Can't use ", tag.em(a),
                                               " annotator:") +
                                    tag.pre(e.message))
                data = (None, None)
            annotator_datas.append(data)

        def _head_row():
            return tag.tr(
                [tag.th(labels[a], class_=a, title=titles[a])
                 for a in annotations] +
                [tag.th(u'\xa0', class_='content')]
            )

        def _body_rows():
            for idx, line in enumerate(_group_lines(stream)):
                row = tag.tr()
                if marks and idx + 1 in marks:
                    row(class_='hilite')
                for annotator, data in annotator_datas:
                    if annotator:
                        annotator.annotate_row(context, row, idx+1, line, data)
                    else:
                        row.append(tag.td())
                row.append(tag.td(line))
                yield row

        return tag.table(class_='code')(
            tag.thead(_head_row()),
            tag.tbody(_body_rows())
        )

    def get_max_preview_size(self):
        """Deprecated: use `max_preview_size` attribute directly."""
        return self.max_preview_size

    def get_charset(self, content='', mimetype=None):
        """Infer the character encoding from the `content` or the `mimetype`.

        `content` is either a `str` or an `unicode` object.
        
        The charset will be determined using this order:
         * from the charset information present in the `mimetype` argument
         * auto-detection of the charset from the `content`
         * the configured `default_charset` 
        """
        if mimetype:
            ctpos = mimetype.find('charset=')
            if ctpos >= 0:
                return mimetype[ctpos + 8:].strip()
        if isinstance(content, str):
            utf = detect_unicode(content)
            if utf is not None:
                return utf
        return self.default_charset

    def get_mimetype(self, filename, content=None):
        """Infer the MIME type from the `filename` or the `content`.

        `content` is either a `str` or an `unicode` object.

        Return the detected MIME type, augmented by the
        charset information (i.e. "<mimetype>; charset=..."),
        or `None` if detection failed.
        """
        # Extend default extension to MIME type mappings with configured ones
        if not self._mime_map:
            self._mime_map = MIME_MAP
            for mapping in self.config['mimeviewer'].getlist('mime_map'):
                if ':' in mapping:
                    assocations = mapping.split(':')
                    for keyword in assocations: # Note: [0] kept on purpose
                        self._mime_map[keyword] = assocations[0]

        mimetype = get_mimetype(filename, content, self._mime_map)
        charset = None
        if mimetype:
            charset = self.get_charset(content, mimetype)
        if mimetype and charset and not 'charset' in mimetype:
            mimetype += '; charset=' + charset
        return mimetype

    def to_utf8(self, content, mimetype=None):
        """Convert an encoded `content` to utf-8.

        ''Deprecated in 0.10. You should use `unicode` strings only.''
        """
        return to_utf8(content, self.get_charset(content, mimetype))

    def to_unicode(self, content, mimetype=None, charset=None):
        """Convert `content` (an encoded `str` object) to an `unicode` object.

        This calls `trac.util.to_unicode` with the `charset` provided,
        or the one obtained by `Mimeview.get_charset()`.
        """
        if not charset:
            charset = self.get_charset(content, mimetype)
        return to_unicode(content, charset)

    def configured_modes_mapping(self, renderer):
        """Return a MIME type to `(mode,quality)` mapping for given `option`"""
        types, option = {}, '%s_modes' % renderer
        for mapping in self.config['mimeviewer'].getlist(option):
            if not mapping:
                continue
            try:
                mimetype, mode, quality = mapping.split(':')
                types[mimetype] = (mode, int(quality))
            except (TypeError, ValueError):
                self.log.warning("Invalid mapping '%s' specified in '%s' "
                                 "option." % (mapping, option))
        return types
    
    def preview_data(self, context, content, length, mimetype, filename,
                     url=None, annotations=None, force_source=False):
        """Prepares a rendered preview of the given `content`.

        Note: `content` will usually be an object with a `read` method.
        """        
        data = {'raw_href': url,
                'max_file_size': self.max_preview_size,
                'max_file_size_reached': False,
                'rendered': None,
                }
        if length >= self.max_preview_size:
            data['max_file_size_reached'] = True
        else:
            result = self.render(context, mimetype, content, filename, url,
                                 annotations, force_source=force_source)
            if isinstance(result, list):
                data['errors'] = result
            else:
                data['rendered'] = result
        return data

    def send_converted(self, req, in_type, content, selector, filename='file'):
        """Helper method for converting `content` and sending it directly.

        `selector` can be either a key or a MIME Type."""
        from trac.web import RequestDone
        content, output_type, ext = self.convert_content(req, in_type,
                                                         content, selector)
        req.send_response(200)
        req.send_header('Content-Type', output_type)
        req.send_header('Content-Disposition', 'filename=%s.%s' % 
                        (filename, ext))
        req.end_headers()
        req.write(content)
        raise RequestDone


def _group_lines(stream):
    space_re = re.compile('(?P<spaces> (?: +))|^(?P<tag><\w+.*?>)?( )')
    def pad_spaces(match):
        m = match.group('spaces')
        if m:
            div, mod = divmod(len(m), 2)
            return div * u'\xa0 ' + mod * u'\xa0'
        return (match.group('tag') or '') + u'\xa0'

    def _generate():
        stack = []
        def _reverse():
            for event in reversed(stack):
                if event[0] is START:
                    yield END, event[1][0], event[2]
                else:
                    yield END_NS, event[1][0], event[2]

        for kind, data, pos in stream:
            if kind is TEXT:
                lines = data.split('\n')
                if lines:
                    # First element
                    for e in stack:
                        yield e
                    yield kind, lines.pop(0), pos
                    for e in _reverse():
                        yield e
                    # Subsequent ones, prefix with \n
                    for line in lines:
                        yield TEXT, '\n', pos
                        for e in stack:
                            yield e
                        yield kind, line, pos
                        for e in _reverse():
                            yield e
            else:
                if kind is START or kind is START_NS:
                    stack.append((kind, data, pos))
                elif kind is END or kind is END_NS:
                    stack.pop()
                else:
                    yield kind, data, pos

    buf = []
    
    # Fix the \n at EOF.
    if not isinstance(stream, list):
        stream = list(stream)
    found_text = False
    
    for i in range(len(stream)-1, -1, -1):
        if stream[i][0] is TEXT:
            e = stream[i]
            # One chance to strip a \n
            if not found_text and e[1].endswith('\n'):
                stream[i] = (e[0], e[1][:-1], e[2])
            if len(e[1]):
                found_text = True
                break
    if not found_text:
        raise StopIteration

    for kind, data, pos in _generate():
        if kind is TEXT and data == '\n':
            yield Stream(buf[:])
            del buf[:]
        else:
            if kind is TEXT:
                data = space_re.sub(pad_spaces, data)
            buf.append((kind, data, pos))
    if buf:
        yield Stream(buf[:])


# -- Default annotators

class LineNumberAnnotator(Component):
    """Text annotator that adds a column with line numbers."""
    implements(IHTMLPreviewAnnotator)

    # ITextAnnotator methods

    def get_annotation_type(self):
        return 'lineno', 'Line', 'Line numbers'

    def get_annotation_data(self, context):
        return None

    def annotate_row(self, context, row, lineno, line, data):
        row.append(tag.th(id='L%s' % lineno)(
            tag.a(lineno, href='#L%s' % lineno)
        ))


# -- Default renderers

class PlainTextRenderer(Component):
    """HTML preview renderer for plain text, and fallback for any kind of text
    for which no more specific renderer is available.
    """
    implements(IHTMLPreviewRenderer)

    expand_tabs = True
    returns_source = True

    TREAT_AS_BINARY = [
        'application/pdf',
        'application/postscript',
        'application/rtf'
    ]

    def get_quality_ratio(self, mimetype):
        if mimetype in self.TREAT_AS_BINARY:
            return 0
        return 1

    def render(self, context, mimetype, content, filename=None, url=None):
        if is_binary(content):
            self.log.debug("Binary data; no preview available")
            return

        self.log.debug("Using default plain text mimeviewer")
        return content_to_unicode(self.env, content, mimetype)


class ImageRenderer(Component):
    """Inline image display. Here we don't need the `content` at all."""
    implements(IHTMLPreviewRenderer)

    def get_quality_ratio(self, mimetype):
        if mimetype.startswith('image/'):
            return 8
        return 0

    def render(self, context, mimetype, content, filename=None, url=None):
        if url:
            return tag.div(tag.img(src=url, alt=filename),
                           class_='image-file')


class WikiTextRenderer(Component):
    """Render files containing Trac's own Wiki formatting markup."""
    implements(IHTMLPreviewRenderer)

    def get_quality_ratio(self, mimetype):
        if mimetype in ('text/x-trac-wiki', 'application/x-trac-wiki'):
            return 8
        return 0

    def render(self, context, mimetype, content, filename=None, url=None):
        from trac.wiki.formatter import format_to_html
        return format_to_html(context, content_to_unicode(self.env, content,
                                                          mimetype))

