Source

trac-ticketlinks / trac / mimeview / api.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
# -*- coding: utf-8 -*-
#
# Copyright (C) 2004-2008 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.resource import Resource
from trac.util import reversed, sorted, Ranges
from trac.util.text import to_utf8, to_unicode
from trac.util.translation import _


__all__ = ['get_mimetype', 'is_binary', 'detect_unicode', 'Mimeview',
           'content_to_unicode', 'Context']

class Context(object):
    """Rendering context.

    A rendering context specifies ''how'' the content should be rendered.
    It holds together all the needed contextual information that will be
    needed by individual renderer components.

    To that end, a context keeps track of the Href instance (`.href`) which
    should be used as a base for building URLs.
    
    It also provides a `PermissionCache`  (`.perm`) which can be used to
    restrict the output so that only the authorized information is shown.
    
    A rendering context may also be associated to some Trac resource which
    will be used as the implicit reference when rendering relative links
    or for retrieving relative content and can be used to retrieve related
    metadata.

    Contexts can be nested, and a new context can be created from an existing
    context using the call syntax. The previous context can be retrieved using
    the `.parent` attribute.
    
    For example, when rendering a wiki text of a wiki page, the context will
    be associated to a resource identifying that wiki page.
    
    If that wiki text contains a `[[TicketQuery]]` wiki macro, the macro will
    set up nested contexts for each matching ticket that will be used for
    rendering the ticket descriptions.

    :since: version 0.11
    """

    def __init__(self, resource, href=None, perm=None):
        """Directly create a `Context`.

        :param resource: the associated resource
        :type resource: `Resource`
        :param href: an `Href` object suitable for creating URLs
        :param perm: a `PermissionCache` object used for restricting the
                     generated output to "authorized" informations only.

        The actual `.perm` attribute of the rendering context will be bound
        to the given `resource` so that fine-grained permission checks will
        apply to that.
        """
        self.parent = None #: The parent context, if any
        self.resource = resource
        self.href = href
        self.perm = resource and perm and perm(resource) or perm

    def from_request(cls, req, resource=None, id=False, version=False,
                     absurls=False):
        """Create a rendering context from a request.

        The `perm` and `href` properties of the context will be initialized
        from the corresponding properties of the request object.

        >>> from trac.test import Mock, MockPerm
        >>> req = Mock(href=Mock(), perm=MockPerm())
        >>> context = Context.from_request(req)
        >>> context.href is req.href
        True
        >>> context.perm is req.perm
        True

        :param req: the HTTP request object
        :param resource: the `Resource` object or realm
        :param id: the resource identifier
        :param version: the resource version
        :param absurls: whether URLs generated by the ``href`` object should
                        be absolute (including the protocol scheme and host
                        name)
        :return: a new rendering context
        :rtype: `Context`
        """
        if req:
            href = absurls and req.abs_href or req.href
            perm = req.perm
        else:
            href = None
            perm = None
        self = cls(Resource(resource, id=id, version=version), href=href,
                   perm=perm)
        self.req = req
        return self
    from_request = classmethod(from_request)

    def __repr__(self):
        path = []
        context = self
        while context:
            if context.resource.realm: # skip toplevel resource 
                path.append(repr(context.resource))
            context = context.parent
        return '<%s %s>' % (type(self).__name__, ' - '.join(reversed(path)))

    def __call__(self, resource, id=False, version=False):
        """Create a nested rendering context.

        `self` will be the parent for the new nested context.

        :param resource: either a `Resource` object or the realm string for a
                         resource specification to be associated to the new
                         context
        :param id: the identifier part of the resource specification
        :param version: the version of the resource specification
        :return: the new context object
        :rtype: `Context`

        >>> context = Context('wiki', 'WikiStart')
        >>> ticket1 = Resource('ticket', 1)
        >>> context('ticket', 1).resource == ticket1
        True
        >>> context(ticket1).resource is ticket1
        True
        """
        resource = Resource(resource, id=id, version=version)
        context = Context(resource, href=self.href, perm=self.perm)
        context.parent = self

        # hack for context instances created by from_request()
        # this is needed because various parts of the code rely on a request
        # object being available, but that will hopefully improve in the
        # future
        if hasattr(self, 'req'):
            context.req = self.req

        return context

    def __contains__(self, resource):
        """Check whether a resource is in the rendering path.

        The primary use for this check is to avoid to render the content of a
        resource if we're already embedded in a context associated to that
        resource.

        :param resource: a `Resource` specification which will be checked for
        """
        context = self
        while context:
            if context.resource and \
                   context.resource.realm == resource.realm and \
                   context.resource.id == resource.id:
                # we don't care about version here
                return True
            context = context.parent


# 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 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` within a Context.

        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 context 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 rendering context.
        
        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 %(old)s '
                              'to %(new)s', old=mimetype, new=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 %(old)s to '
                          '%(new)s', old=mimetype, new=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 ''
        if not isinstance(context, Context):
            # backwards compatibility: the first argument used to be the
            # request prior to 0.11
            context = Context.from_request(context)

        # 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):
        from trac.web.chrome import add_warning
        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))
                add_warning(context.req, 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(self.env, context,
                              content_to_unicode(self.env, content, mimetype))