Edgewall Software

Extension Point : IHTMLPreviewRenderer

InterfaceIHTMLPreviewRendererSince0.9
Moduletrac.mimeviewSourceapi.py

The IHTMLPreviewRenderer allows previewing files as HTML with syntax coloring.

Purpose

Trac provides support for previewing files (attachments, files stored in version control) in the browser as HTML with syntax coloring. The same support is also available for embedding via WikiProcessors syntax. Plugins can add support for additional kinds of previews by implementing IHTMLPreviewRenderer.

Usage

Implementing the interface follows the standard guidelines found in TracDev/ComponentArchitecture and of course TracDev/PluginDevelopment.

The implementation has to report how well it supports a given mime type when queried. It might then be called (if no better support is available) to render a preview.

Any module can utilize such a preview rendering by calling Mimeview.render(...) or Mimeview.preview_data(...) (typically used with the preview_file.html template). Core use cases are:

Examples

The following minimal example renders non-binary content as all caps plain text:

from trac.core import implements, Component
from trac.mimeview.api import Mimeview, IHTMLPreviewRenderer, content_to_unicode, is_binary

class AllCapsPlainTextRenderer(Component):
        
    implements(IHTMLPreviewRenderer)

    expand_tabs = True
    returns_source = True

    def get_quality_ratio(self, mimetype):
        if mimetype in Mimeview(self.env).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 all caps plain text mimeviewer")
        return str.upper(content_to_unicode(self.env, content, mimetype))

Available Implementations

In Trac:

PlainTextRenderer Renders anything as plain text as a fallback.
ImageRenderer Renders an image inline (using an img tag).
WikiTextRenderer Renders a Trac Wiki page.
PatchRenderer Renders patches in unified diff format.