|
1 """mime type transformation engine for cubicweb, based on mtconverter |
|
2 |
|
3 :organization: Logilab |
|
4 :copyright: 2001-2008 LOGILAB S.A. (Paris, FRANCE), all rights reserved. |
|
5 :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
|
6 """ |
|
7 __docformat__ = "restructuredtext en" |
|
8 |
|
9 from logilab import mtconverter |
|
10 |
|
11 from logilab.mtconverter.engine import TransformEngine |
|
12 from logilab.mtconverter.transform import Transform |
|
13 from logilab.mtconverter import (register_base_transforms, |
|
14 register_pil_transforms, |
|
15 register_pygments_transforms) |
|
16 |
|
17 from cubicweb.common.uilib import rest_publish, html_publish, remove_html_tags |
|
18 |
|
19 HTML_MIMETYPES = ('text/html', 'text/xhtml', 'application/xhtml+xml') |
|
20 |
|
21 # CubicWeb specific transformations |
|
22 |
|
23 class rest_to_html(Transform): |
|
24 inputs = ('text/rest', 'text/x-rst') |
|
25 output = 'text/html' |
|
26 def _convert(self, trdata): |
|
27 return rest_publish(trdata.appobject, trdata.decode()) |
|
28 |
|
29 class html_to_html(Transform): |
|
30 inputs = HTML_MIMETYPES |
|
31 output = 'text/html' |
|
32 def _convert(self, trdata): |
|
33 return html_publish(trdata.appobject, trdata.data) |
|
34 |
|
35 class ept_to_html(Transform): |
|
36 inputs = ('text/cubicweb-page-template',) |
|
37 output = 'text/html' |
|
38 output_encoding = 'utf-8' |
|
39 def _convert(self, trdata): |
|
40 from cubicweb.common.tal import compile_template |
|
41 value = trdata.encode(self.output_encoding) |
|
42 return trdata.appobject.tal_render(compile_template(value), {}) |
|
43 |
|
44 |
|
45 # Instantiate and configure the transformation engine |
|
46 |
|
47 mtconverter.UNICODE_POLICY = 'replace' |
|
48 |
|
49 ENGINE = TransformEngine() |
|
50 ENGINE.add_transform(rest_to_html()) |
|
51 ENGINE.add_transform(html_to_html()) |
|
52 ENGINE.add_transform(ept_to_html()) |
|
53 |
|
54 if register_pil_transforms(ENGINE, verb=False): |
|
55 HAS_PIL_TRANSFORMS = True |
|
56 else: |
|
57 HAS_PIL_TRANSFORMS = False |
|
58 |
|
59 try: |
|
60 from logilab.mtconverter.transforms import pygmentstransforms |
|
61 for mt in ('text/plain',) + HTML_MIMETYPES: |
|
62 try: |
|
63 pygmentstransforms.mimetypes.remove(mt) |
|
64 except ValueError: |
|
65 continue |
|
66 register_pygments_transforms(ENGINE, verb=False) |
|
67 |
|
68 def patch_convert(cls): |
|
69 def _convert(self, trdata, origconvert=cls._convert): |
|
70 try: |
|
71 trdata.appobject.req.add_css('pygments.css') |
|
72 except AttributeError: # session has no add_css, only http request |
|
73 pass |
|
74 return origconvert(self, trdata) |
|
75 cls._convert = _convert |
|
76 patch_convert(pygmentstransforms.PygmentsHTMLTransform) |
|
77 |
|
78 HAS_PYGMENTS_TRANSFORMS = True |
|
79 except ImportError: |
|
80 HAS_PYGMENTS_TRANSFORMS = False |
|
81 |
|
82 register_base_transforms(ENGINE, verb=False) |