author | Aurelien Campeas <aurelien.campeas@logilab.fr> |
Wed, 17 Jun 2009 20:46:37 +0200 | |
branch | stable |
changeset 2114 | 862f27d94af4 |
parent 1977 | 606923dff11b |
child 2208 | 1c73148ed912 |
permissions | -rw-r--r-- |
0 | 1 |
# -*- coding: utf-8 -*- |
2 |
"""user interface libraries |
|
3 |
||
4 |
contains some functions designed to help implementation of cubicweb user interface |
|
5 |
||
6 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1647
diff
changeset
|
7 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 8 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1647
diff
changeset
|
9 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 10 |
""" |
11 |
__docformat__ = "restructuredtext en" |
|
12 |
||
13 |
import csv |
|
14 |
import re |
|
15 |
from urllib import quote as urlquote |
|
1635
866563e2d0fc
don't depends on simplejson outside web/
sylvain.thenault@logilab.fr
parents:
1623
diff
changeset
|
16 |
from StringIO import StringIO |
0 | 17 |
|
362
a6a319f000c3
use mtconverter's html_unescape rather than saxutils' escape to deal with any html entity
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
350
diff
changeset
|
18 |
from logilab.mtconverter import html_escape, html_unescape |
0 | 19 |
|
709 | 20 |
from cubicweb.utils import ustrftime |
0 | 21 |
|
22 |
def rql_for_eid(eid): |
|
23 |
"""return the rql query necessary to fetch entity with the given eid. This |
|
24 |
function should only be used to generate link with rql inside, not to give |
|
25 |
to cursor.execute (in which case you won't benefit from rql cache). |
|
26 |
||
27 |
:Parameters: |
|
28 |
- `eid`: the eid of the entity we should search |
|
29 |
:rtype: str |
|
30 |
:return: the rql query |
|
31 |
""" |
|
32 |
return 'Any X WHERE X eid %s' % eid |
|
33 |
||
34 |
||
35 |
def printable_value(req, attrtype, value, props=None, displaytime=True): |
|
36 |
"""return a displayable value (i.e. unicode string)""" |
|
37 |
if value is None or attrtype == 'Bytes': |
|
38 |
return u'' |
|
39 |
if attrtype == 'String': |
|
40 |
# don't translate empty value if you don't want strange results |
|
41 |
if props is not None and value and props.get('internationalizable'): |
|
42 |
return req._(value) |
|
1581
80ee6397c087
fix rest import, html_escape in null rest_publish
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
43 |
|
0 | 44 |
return value |
45 |
if attrtype == 'Date': |
|
46 |
return ustrftime(value, req.property_value('ui.date-format')) |
|
47 |
if attrtype == 'Time': |
|
48 |
return ustrftime(value, req.property_value('ui.time-format')) |
|
49 |
if attrtype == 'Datetime': |
|
50 |
if not displaytime: |
|
51 |
return ustrftime(value, req.property_value('ui.date-format')) |
|
52 |
return ustrftime(value, req.property_value('ui.datetime-format')) |
|
53 |
if attrtype == 'Boolean': |
|
54 |
if value: |
|
55 |
return req._('yes') |
|
56 |
return req._('no') |
|
57 |
if attrtype == 'Float': |
|
58 |
value = req.property_value('ui.float-format') % value |
|
59 |
return unicode(value) |
|
60 |
||
61 |
||
62 |
# text publishing ############################################################# |
|
63 |
||
64 |
try: |
|
1581
80ee6397c087
fix rest import, html_escape in null rest_publish
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
65 |
from cubicweb.ext.rest import rest_publish # pylint: disable-msg=W0611 |
0 | 66 |
except ImportError: |
67 |
def rest_publish(entity, data): |
|
68 |
"""default behaviour if docutils was not found""" |
|
1581
80ee6397c087
fix rest import, html_escape in null rest_publish
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
69 |
return html_escape(data) |
80ee6397c087
fix rest import, html_escape in null rest_publish
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
70 |
|
0 | 71 |
TAG_PROG = re.compile(r'</?.*?>', re.U) |
72 |
def remove_html_tags(text): |
|
73 |
"""Removes HTML tags from text |
|
74 |
||
75 |
>>> remove_html_tags('<td>hi <a href="http://www.google.fr">world</a></td>') |
|
76 |
'hi world' |
|
77 |
>>> |
|
78 |
""" |
|
79 |
return TAG_PROG.sub('', text) |
|
80 |
||
81 |
||
82 |
REF_PROG = re.compile(r"<ref\s+rql=([\'\"])([^\1]*?)\1\s*>([^<]*)</ref>", re.U) |
|
83 |
def _subst_rql(view, obj): |
|
84 |
delim, rql, descr = obj.groups() |
|
85 |
return u'<a href="%s">%s</a>' % (view.build_url(rql=rql), descr) |
|
86 |
||
87 |
def html_publish(view, text): |
|
88 |
"""replace <ref rql=''> links by <a href="...">""" |
|
89 |
if not text: |
|
90 |
return u'' |
|
91 |
return REF_PROG.sub(lambda obj, view=view:_subst_rql(view, obj), text) |
|
92 |
||
277
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
93 |
# fallback implementation, nicer one defined below if lxml is available |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
94 |
def soup2xhtml(data, encoding): |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
95 |
return data |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
96 |
|
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
97 |
# fallback implementation, nicer one defined below if lxml> 2.0 is available |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
98 |
def safe_cut(text, length): |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
99 |
"""returns a string of length <length> based on <text>, removing any html |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
100 |
tags from given text if cut is necessary.""" |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
101 |
if text is None: |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
102 |
return u'' |
362
a6a319f000c3
use mtconverter's html_unescape rather than saxutils' escape to deal with any html entity
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
350
diff
changeset
|
103 |
noenttext = html_unescape(text) |
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
104 |
text_nohtml = remove_html_tags(noenttext) |
277
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
105 |
# try to keep html tags if text is short enough |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
106 |
if len(text_nohtml) <= length: |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
107 |
return text |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
108 |
# else if un-tagged text is too long, cut it |
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
109 |
return html_escape(text_nohtml[:length] + u'...') |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
110 |
|
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
111 |
fallback_safe_cut = safe_cut |
277
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
112 |
|
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
113 |
|
0 | 114 |
try: |
115 |
from lxml import etree |
|
228
27b958dc72ae
[lxml] lxml version < 2 does not provide an iter method on some elements
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
165
diff
changeset
|
116 |
except (ImportError, AttributeError): |
0 | 117 |
# gae environment: lxml not availabel |
277
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
118 |
pass |
0 | 119 |
else: |
120 |
||
121 |
def soup2xhtml(data, encoding): |
|
122 |
"""tidy (at least try) html soup and return the result |
|
123 |
Note: the function considers a string with no surrounding tag as valid |
|
124 |
if <div>`data`</div> can be parsed by an XML parser |
|
125 |
""" |
|
126 |
xmltree = etree.HTML('<div>%s</div>' % data) |
|
127 |
# NOTE: lxml 1.1 (etch platforms) doesn't recognize |
|
128 |
# the encoding=unicode parameter (lxml 2.0 does), this is |
|
129 |
# why we specify an encoding and re-decode to unicode later |
|
130 |
body = etree.tostring(xmltree[0], encoding=encoding) |
|
131 |
# remove <body> and </body> and decode to unicode |
|
132 |
return body[11:-13].decode(encoding) |
|
133 |
||
277
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
134 |
if hasattr(etree.HTML('<div>test</div>'), 'iter'): |
165 | 135 |
|
277
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
136 |
def safe_cut(text, length): |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
137 |
"""returns an html document of length <length> based on <text>, |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
138 |
and cut is necessary. |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
139 |
""" |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
140 |
if text is None: |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
141 |
return u'' |
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
142 |
dom = etree.HTML(text) |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
143 |
curlength = 0 |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
144 |
add_ellipsis = False |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
145 |
for element in dom.iter(): |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
146 |
if curlength >= length: |
277
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
147 |
parent = element.getparent() |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
148 |
parent.remove(element) |
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
149 |
if curlength == length and (element.text or element.tail): |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
150 |
add_ellipsis = True |
277
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
151 |
else: |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
152 |
if element.text is not None: |
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
153 |
element.text = cut(element.text, length - curlength) |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
154 |
curlength += len(element.text) |
277
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
155 |
if element.tail is not None: |
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
156 |
if curlength < length: |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
157 |
element.tail = cut(element.tail, length - curlength) |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
158 |
curlength += len(element.tail) |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
159 |
elif curlength == length: |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
160 |
element.tail = '...' |
277
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
161 |
else: |
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
162 |
element.tail = '' |
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
163 |
text = etree.tounicode(dom[0])[6:-7] # remove wrapping <body></body> |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
164 |
if add_ellipsis: |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
165 |
return text + u'...' |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
166 |
return text |
1157
81a383cdda5c
text_cut() accepts a gotoperiod parameter
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
927
diff
changeset
|
167 |
|
81a383cdda5c
text_cut() accepts a gotoperiod parameter
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
927
diff
changeset
|
168 |
def text_cut(text, nbwords=30, gotoperiod=True): |
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
169 |
"""from the given plain text, return a text with at least <nbwords> words, |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
170 |
trying to go to the end of the current sentence. |
277
a11a3c231050
fix lxml is available, we can have a nicer version of soup2xhtml even if its lxml < 2.0
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
228
diff
changeset
|
171 |
|
1157
81a383cdda5c
text_cut() accepts a gotoperiod parameter
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
927
diff
changeset
|
172 |
:param nbwords: the minimum number of words required |
81a383cdda5c
text_cut() accepts a gotoperiod parameter
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
927
diff
changeset
|
173 |
:param gotoperiod: specifies if the function should try to go to |
81a383cdda5c
text_cut() accepts a gotoperiod parameter
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
927
diff
changeset
|
174 |
the first period after the cut (i.e. finish |
81a383cdda5c
text_cut() accepts a gotoperiod parameter
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
927
diff
changeset
|
175 |
the sentence if possible) |
81a383cdda5c
text_cut() accepts a gotoperiod parameter
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
927
diff
changeset
|
176 |
|
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
177 |
Note that spaces are normalized. |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
178 |
""" |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
179 |
if text is None: |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
180 |
return u'' |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
181 |
words = text.split() |
927
bfcc610c3d5e
text_cut must return unicode not string
Stephanie Marcu <stephanie.marcu@logilab.fr>
parents:
525
diff
changeset
|
182 |
text = u' '.join(words) # normalize spaces |
1157
81a383cdda5c
text_cut() accepts a gotoperiod parameter
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
927
diff
changeset
|
183 |
textlength = minlength = len(' '.join(words[:nbwords])) |
81a383cdda5c
text_cut() accepts a gotoperiod parameter
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
927
diff
changeset
|
184 |
if gotoperiod: |
81a383cdda5c
text_cut() accepts a gotoperiod parameter
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
927
diff
changeset
|
185 |
textlength = text.find('.', minlength) + 1 |
81a383cdda5c
text_cut() accepts a gotoperiod parameter
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
927
diff
changeset
|
186 |
if textlength == 0: # no period found |
81a383cdda5c
text_cut() accepts a gotoperiod parameter
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
927
diff
changeset
|
187 |
textlength = minlength |
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
188 |
return text[:textlength] |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
189 |
|
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
190 |
def cut(text, length): |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
191 |
"""returns a string of a maximum length <length> based on <text> |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
192 |
(approximatively, since if text has been cut, '...' is added to the end of the string, |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
193 |
resulting in a string of len <length> + 3) |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
194 |
""" |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
195 |
if text is None: |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
196 |
return u'' |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
197 |
if len(text) <= length: |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
198 |
return text |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
199 |
# else if un-tagged text is too long, cut it |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
200 |
return text[:length] + u'...' |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
201 |
|
165 | 202 |
|
1581
80ee6397c087
fix rest import, html_escape in null rest_publish
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
203 |
|
0 | 204 |
# HTML generation helper functions ############################################ |
205 |
||
1623 | 206 |
def simple_sgml_tag(tag, content=None, escapecontent=True, **attrs): |
525
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
207 |
"""generation of a simple sgml tag (eg without children tags) easier |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
208 |
|
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
209 |
content and attributes will be escaped |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
210 |
""" |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
211 |
value = u'<%s' % tag |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
212 |
if attrs: |
980
59552ba2015f
more tags, map klass -> class avoiding needs to use **dict
sylvain.thenault@logilab.fr
parents:
862
diff
changeset
|
213 |
try: |
59552ba2015f
more tags, map klass -> class avoiding needs to use **dict
sylvain.thenault@logilab.fr
parents:
862
diff
changeset
|
214 |
attrs['class'] = attrs.pop('klass') |
59552ba2015f
more tags, map klass -> class avoiding needs to use **dict
sylvain.thenault@logilab.fr
parents:
862
diff
changeset
|
215 |
except KeyError: |
59552ba2015f
more tags, map klass -> class avoiding needs to use **dict
sylvain.thenault@logilab.fr
parents:
862
diff
changeset
|
216 |
pass |
525
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
217 |
value += u' ' + u' '.join(u'%s="%s"' % (attr, html_escape(unicode(value))) |
1647
9936aca2453d
sort attribute for testing purpose
sylvain.thenault@logilab.fr
parents:
1646
diff
changeset
|
218 |
for attr, value in sorted(attrs.items()) |
862
ee560986e211
mini improvement to simple_sgml_tag: ignore attributes for which the value is None
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
709
diff
changeset
|
219 |
if value is not None) |
525
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
220 |
if content: |
1623 | 221 |
if escapecontent: |
222 |
content = html_escape(unicode(content)) |
|
223 |
value += u'>%s</%s>' % (content, tag) |
|
525
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
224 |
else: |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
225 |
value += u'/>' |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
226 |
return value |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
227 |
|
0 | 228 |
def tooltipize(text, tooltip, url=None): |
229 |
"""make an HTML tooltip""" |
|
230 |
url = url or '#' |
|
231 |
return u'<a href="%s" title="%s">%s</a>' % (url, tooltip, text) |
|
232 |
||
233 |
def toggle_action(nodeid): |
|
234 |
"""builds a HTML link that uses the js toggleVisibility function""" |
|
235 |
return u"javascript: toggleVisibility('%s')" % nodeid |
|
236 |
||
237 |
def toggle_link(nodeid, label): |
|
238 |
"""builds a HTML link that uses the js toggleVisibility function""" |
|
239 |
return u'<a href="%s">%s</a>' % (toggle_action(nodeid), label) |
|
240 |
||
241 |
||
242 |
def ureport_as_html(layout): |
|
243 |
from logilab.common.ureports import HTMLWriter |
|
244 |
formater = HTMLWriter(True) |
|
245 |
stream = StringIO() #UStringIO() don't want unicode assertion |
|
246 |
formater.format(layout, stream) |
|
247 |
res = stream.getvalue() |
|
248 |
if isinstance(res, str): |
|
249 |
res = unicode(res, 'UTF8') |
|
250 |
return res |
|
251 |
||
252 |
def render_HTML_tree(tree, selected_node=None, render_node=None, caption=None): |
|
253 |
""" |
|
254 |
Generate a pure HTML representation of a tree given as an instance |
|
255 |
of a logilab.common.tree.Node |
|
256 |
||
257 |
selected_node is the currently selected node (if any) which will |
|
258 |
have its surrounding <div> have id="selected" (which default |
|
259 |
to a bold border libe with the default CSS). |
|
260 |
||
261 |
render_node is a function that should take a Node content (Node.id) |
|
262 |
as parameter and should return a string (what will be displayed |
|
263 |
in the cell). |
|
264 |
||
265 |
Warning: proper rendering of the generated html code depends on html_tree.css |
|
266 |
""" |
|
267 |
tree_depth = tree.depth_down() |
|
268 |
if render_node is None: |
|
269 |
render_node = str |
|
270 |
||
271 |
# helper function that build a matrix from the tree, like: |
|
272 |
# +------+-----------+-----------+ |
|
273 |
# | root | child_1_1 | child_2_1 | |
|
274 |
# | root | child_1_1 | child_2_2 | |
|
275 |
# | root | child_1_2 | | |
|
276 |
# | root | child_1_3 | child_2_3 | |
|
277 |
# | root | child_1_3 | child_2_4 | |
|
278 |
# +------+-----------+-----------+ |
|
279 |
# from: |
|
280 |
# root -+- child_1_1 -+- child_2_1 |
|
281 |
# | | |
|
282 |
# | +- child_2_2 |
|
283 |
# +- child_1_2 |
|
284 |
# | |
|
285 |
# +- child1_3 -+- child_2_3 |
|
286 |
# | |
|
287 |
# +- child_2_2 |
|
288 |
def build_matrix(path, matrix): |
|
289 |
if path[-1].is_leaf(): |
|
290 |
matrix.append(path[:]) |
|
291 |
else: |
|
292 |
for child in path[-1].children: |
|
293 |
build_matrix(path[:] + [child], matrix) |
|
1581
80ee6397c087
fix rest import, html_escape in null rest_publish
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
294 |
|
0 | 295 |
matrix = [] |
296 |
build_matrix([tree], matrix) |
|
297 |
||
298 |
# make all lines in the matrix have the same number of columns |
|
299 |
for line in matrix: |
|
300 |
line.extend([None]*(tree_depth-len(line))) |
|
301 |
for i in range(len(matrix)-1, 0, -1): |
|
302 |
prev_line, line = matrix[i-1:i+1] |
|
303 |
for j in range(len(line)): |
|
304 |
if line[j] == prev_line[j]: |
|
305 |
line[j] = None |
|
306 |
||
307 |
# We build the matrix of link types (between 2 cells on a line of the matrix) |
|
308 |
# link types are : |
|
309 |
link_types = {(True, True, True ): 1, # T |
|
310 |
(False, False, True ): 2, # | |
|
311 |
(False, True, True ): 3, # + (actually, vert. bar with horiz. bar on the right) |
|
312 |
(False, True, False): 4, # L |
|
313 |
(True, True, False): 5, # - |
|
314 |
} |
|
315 |
links = [] |
|
316 |
for i, line in enumerate(matrix): |
|
317 |
links.append([]) |
|
318 |
for j in range(tree_depth-1): |
|
319 |
cell_11 = line[j] is not None |
|
320 |
cell_12 = line[j+1] is not None |
|
321 |
cell_21 = line[j+1] is not None and line[j+1].next_sibling() is not None |
|
322 |
link_type = link_types.get((cell_11, cell_12, cell_21), 0) |
|
1132 | 323 |
if link_type == 0 and i > 0 and links[i-1][j] in (1, 2, 3): |
0 | 324 |
link_type = 2 |
325 |
links[-1].append(link_type) |
|
1581
80ee6397c087
fix rest import, html_escape in null rest_publish
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
326 |
|
0 | 327 |
|
1581
80ee6397c087
fix rest import, html_escape in null rest_publish
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
328 |
# We can now generate the HTML code for the <table> |
0 | 329 |
s = u'<table class="tree">\n' |
330 |
if caption: |
|
331 |
s += '<caption>%s</caption>\n' % caption |
|
332 |
||
333 |
for i, link_line in enumerate(links): |
|
334 |
line = matrix[i] |
|
335 |
||
336 |
s += '<tr>' |
|
337 |
for j, link_cell in enumerate(link_line): |
|
338 |
cell = line[j] |
|
339 |
if cell: |
|
340 |
if cell.id == selected_node: |
|
341 |
s += '<td class="tree_cell" rowspan="2"><div id="selected" class="tree_cell">%s</div></td>' % (render_node(cell.id)) |
|
342 |
else: |
|
343 |
s += '<td class="tree_cell" rowspan="2"><div class="tree_cell">%s</div></td>' % (render_node(cell.id)) |
|
344 |
else: |
|
345 |
s += '<td rowspan="2"> </td>' |
|
346 |
s += '<td class="tree_cell_%d_1"> </td>' % link_cell |
|
347 |
s += '<td class="tree_cell_%d_2"> </td>' % link_cell |
|
1581
80ee6397c087
fix rest import, html_escape in null rest_publish
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
348 |
|
0 | 349 |
cell = line[-1] |
350 |
if cell: |
|
351 |
if cell.id == selected_node: |
|
352 |
s += '<td class="tree_cell" rowspan="2"><div id="selected" class="tree_cell">%s</div></td>' % (render_node(cell.id)) |
|
353 |
else: |
|
354 |
s += '<td class="tree_cell" rowspan="2"><div class="tree_cell">%s</div></td>' % (render_node(cell.id)) |
|
355 |
else: |
|
356 |
s += '<td rowspan="2"> </td>' |
|
357 |
||
358 |
s += '</tr>\n' |
|
359 |
if link_line: |
|
360 |
s += '<tr>' |
|
361 |
for j, link_cell in enumerate(link_line): |
|
362 |
s += '<td class="tree_cell_%d_3"> </td>' % link_cell |
|
363 |
s += '<td class="tree_cell_%d_4"> </td>' % link_cell |
|
364 |
s += '</tr>\n' |
|
365 |
||
366 |
s += '</table>' |
|
367 |
return s |
|
368 |
||
369 |
||
370 |
||
371 |
# traceback formatting ######################################################## |
|
372 |
||
373 |
import traceback |
|
374 |
||
375 |
def rest_traceback(info, exception): |
|
376 |
"""return a ReST formated traceback""" |
|
377 |
res = [u'Traceback\n---------\n::\n'] |
|
378 |
for stackentry in traceback.extract_tb(info[2]): |
|
379 |
res.append(u'\tFile %s, line %s, function %s' % tuple(stackentry[:3])) |
|
380 |
if stackentry[3]: |
|
381 |
res.append(u'\t %s' % stackentry[3].decode('utf-8', 'replace')) |
|
382 |
res.append(u'\n') |
|
383 |
try: |
|
384 |
res.append(u'\t Error: %s\n' % exception) |
|
385 |
except: |
|
386 |
pass |
|
387 |
return u'\n'.join(res) |
|
388 |
||
389 |
||
390 |
def html_traceback(info, exception, title='', |
|
391 |
encoding='ISO-8859-1', body=''): |
|
392 |
""" return an html formatted traceback from python exception infos. |
|
393 |
""" |
|
394 |
tcbk = info[2] |
|
395 |
stacktb = traceback.extract_tb(tcbk) |
|
396 |
strings = [] |
|
397 |
if body: |
|
398 |
strings.append(u'<div class="error_body">') |
|
399 |
# FIXME |
|
400 |
strings.append(body) |
|
401 |
strings.append(u'</div>') |
|
402 |
if title: |
|
403 |
strings.append(u'<h1 class="error">%s</h1>'% html_escape(title)) |
|
404 |
try: |
|
405 |
strings.append(u'<p class="error">%s</p>' % html_escape(str(exception)).replace("\n","<br />")) |
|
406 |
except UnicodeError: |
|
407 |
pass |
|
408 |
strings.append(u'<div class="error_traceback">') |
|
409 |
for index, stackentry in enumerate(stacktb): |
|
410 |
strings.append(u'<b>File</b> <b class="file">%s</b>, <b>line</b> ' |
|
411 |
u'<b class="line">%s</b>, <b>function</b> ' |
|
412 |
u'<b class="function">%s</b>:<br/>'%( |
|
413 |
html_escape(stackentry[0]), stackentry[1], html_escape(stackentry[2]))) |
|
414 |
if stackentry[3]: |
|
415 |
string = html_escape(stackentry[3]).decode('utf-8', 'replace') |
|
416 |
strings.append(u' %s<br/>\n' % (string)) |
|
417 |
# add locals info for each entry |
|
418 |
try: |
|
419 |
local_context = tcbk.tb_frame.f_locals |
|
420 |
html_info = [] |
|
421 |
chars = 0 |
|
422 |
for name, value in local_context.iteritems(): |
|
423 |
value = html_escape(repr(value)) |
|
424 |
info = u'<span class="name">%s</span>=%s, ' % (name, value) |
|
425 |
line_length = len(name) + len(value) |
|
426 |
chars += line_length |
|
427 |
# 150 is the result of *years* of research ;-) (CSS might be helpful here) |
|
428 |
if chars > 150: |
|
429 |
info = u'<br/>' + info |
|
430 |
chars = line_length |
|
431 |
html_info.append(info) |
|
432 |
boxid = 'ctxlevel%d' % index |
|
433 |
strings.append(u'[%s]' % toggle_link(boxid, '+')) |
|
434 |
strings.append(u'<div id="%s" class="pycontext hidden">%s</div>' % |
|
435 |
(boxid, ''.join(html_info))) |
|
436 |
tcbk = tcbk.tb_next |
|
437 |
except Exception: |
|
1581
80ee6397c087
fix rest import, html_escape in null rest_publish
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
438 |
pass # doesn't really matter if we have no context info |
0 | 439 |
strings.append(u'</div>') |
440 |
return '\n'.join(strings) |
|
441 |
||
442 |
# csv files / unicode support ################################################# |
|
443 |
||
444 |
class UnicodeCSVWriter: |
|
445 |
"""proxies calls to csv.writer.writerow to be able to deal with unicode""" |
|
1581
80ee6397c087
fix rest import, html_escape in null rest_publish
sylvain.thenault@logilab.fr
parents:
1263
diff
changeset
|
446 |
|
0 | 447 |
def __init__(self, wfunc, encoding, **kwargs): |
448 |
self.writer = csv.writer(self, **kwargs) |
|
449 |
self.wfunc = wfunc |
|
450 |
self.encoding = encoding |
|
451 |
||
452 |
def write(self, data): |
|
453 |
self.wfunc(data) |
|
454 |
||
455 |
def writerow(self, row): |
|
456 |
csvrow = [] |
|
457 |
for elt in row: |
|
458 |
if isinstance(elt, unicode): |
|
459 |
csvrow.append(elt.encode(self.encoding)) |
|
460 |
else: |
|
461 |
csvrow.append(str(elt)) |
|
462 |
self.writer.writerow(csvrow) |
|
463 |
||
464 |
def writerows(self, rows): |
|
465 |
for row in rows: |
|
466 |
self.writerow(row) |
|
467 |
||
468 |
||
469 |
# some decorators ############################################################# |
|
470 |
||
471 |
class limitsize(object): |
|
472 |
def __init__(self, maxsize): |
|
473 |
self.maxsize = maxsize |
|
474 |
||
475 |
def __call__(self, function): |
|
476 |
def newfunc(*args, **kwargs): |
|
477 |
ret = function(*args, **kwargs) |
|
478 |
if isinstance(ret, basestring): |
|
479 |
return ret[:self.maxsize] |
|
480 |
return ret |
|
481 |
return newfunc |
|
482 |
||
483 |
||
484 |
def htmlescape(function): |
|
485 |
def newfunc(*args, **kwargs): |
|
486 |
ret = function(*args, **kwargs) |
|
487 |
assert isinstance(ret, basestring) |
|
488 |
return html_escape(ret) |
|
489 |
return newfunc |