author | Arthur Lutz <arthur.lutz@logilab.fr> |
Tue, 10 Feb 2009 18:12:10 +0100 | |
changeset 592 | aae01d81c713 |
parent 525 | bd4e03297cf0 |
child 708 | b4728112625f |
child 927 | bfcc610c3d5e |
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 |
|
525
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
7 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), all rights reserved. |
0 | 8 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
9 |
""" |
|
10 |
__docformat__ = "restructuredtext en" |
|
11 |
||
12 |
import csv |
|
13 |
import decimal |
|
14 |
import locale |
|
15 |
import re |
|
16 |
from urllib import quote as urlquote |
|
17 |
from cStringIO import StringIO |
|
164 | 18 |
from copy import deepcopy |
0 | 19 |
|
20 |
import simplejson |
|
21 |
||
22 |
from mx.DateTime import DateTimeType, DateTimeDeltaType |
|
23 |
||
24 |
from logilab.common.textutils import unormalize |
|
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
|
25 |
from logilab.mtconverter import html_escape, html_unescape |
0 | 26 |
|
27 |
def ustrftime(date, fmt='%Y-%m-%d'): |
|
28 |
"""like strftime, but returns a unicode string instead of an encoded |
|
29 |
string which may be problematic with localized date. |
|
30 |
|
|
31 |
encoding is guessed by locale.getpreferredencoding() |
|
32 |
""" |
|
33 |
# date format may depend on the locale |
|
34 |
encoding = locale.getpreferredencoding(do_setlocale=False) or 'UTF-8' |
|
35 |
return unicode(date.strftime(fmt), encoding) |
|
36 |
||
37 |
||
38 |
def rql_for_eid(eid): |
|
39 |
"""return the rql query necessary to fetch entity with the given eid. This |
|
40 |
function should only be used to generate link with rql inside, not to give |
|
41 |
to cursor.execute (in which case you won't benefit from rql cache). |
|
42 |
||
43 |
:Parameters: |
|
44 |
- `eid`: the eid of the entity we should search |
|
45 |
:rtype: str |
|
46 |
:return: the rql query |
|
47 |
""" |
|
48 |
return 'Any X WHERE X eid %s' % eid |
|
49 |
||
50 |
||
51 |
def printable_value(req, attrtype, value, props=None, displaytime=True): |
|
52 |
"""return a displayable value (i.e. unicode string)""" |
|
53 |
if value is None or attrtype == 'Bytes': |
|
54 |
return u'' |
|
55 |
if attrtype == 'String': |
|
56 |
# don't translate empty value if you don't want strange results |
|
57 |
if props is not None and value and props.get('internationalizable'): |
|
58 |
return req._(value) |
|
59 |
||
60 |
return value |
|
61 |
if attrtype == 'Date': |
|
62 |
return ustrftime(value, req.property_value('ui.date-format')) |
|
63 |
if attrtype == 'Time': |
|
64 |
return ustrftime(value, req.property_value('ui.time-format')) |
|
65 |
if attrtype == 'Datetime': |
|
66 |
if not displaytime: |
|
67 |
return ustrftime(value, req.property_value('ui.date-format')) |
|
68 |
return ustrftime(value, req.property_value('ui.datetime-format')) |
|
69 |
if attrtype == 'Boolean': |
|
70 |
if value: |
|
71 |
return req._('yes') |
|
72 |
return req._('no') |
|
73 |
if attrtype == 'Float': |
|
74 |
value = req.property_value('ui.float-format') % value |
|
75 |
return unicode(value) |
|
76 |
||
77 |
||
78 |
# text publishing ############################################################# |
|
79 |
||
80 |
try: |
|
81 |
from cubicweb.common.rest import rest_publish # pylint: disable-msg=W0611 |
|
82 |
except ImportError: |
|
83 |
def rest_publish(entity, data): |
|
84 |
"""default behaviour if docutils was not found""" |
|
85 |
return data |
|
86 |
||
87 |
TAG_PROG = re.compile(r'</?.*?>', re.U) |
|
88 |
def remove_html_tags(text): |
|
89 |
"""Removes HTML tags from text |
|
90 |
||
91 |
>>> remove_html_tags('<td>hi <a href="http://www.google.fr">world</a></td>') |
|
92 |
'hi world' |
|
93 |
>>> |
|
94 |
""" |
|
95 |
return TAG_PROG.sub('', text) |
|
96 |
||
97 |
||
98 |
REF_PROG = re.compile(r"<ref\s+rql=([\'\"])([^\1]*?)\1\s*>([^<]*)</ref>", re.U) |
|
99 |
def _subst_rql(view, obj): |
|
100 |
delim, rql, descr = obj.groups() |
|
101 |
return u'<a href="%s">%s</a>' % (view.build_url(rql=rql), descr) |
|
102 |
||
103 |
def html_publish(view, text): |
|
104 |
"""replace <ref rql=''> links by <a href="...">""" |
|
105 |
if not text: |
|
106 |
return u'' |
|
107 |
return REF_PROG.sub(lambda obj, view=view:_subst_rql(view, obj), text) |
|
108 |
||
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
|
109 |
# 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
|
110 |
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
|
111 |
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
|
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 |
# 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
|
114 |
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
|
115 |
"""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
|
116 |
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
|
117 |
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
|
118 |
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
|
119 |
noenttext = html_unescape(text) |
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
120 |
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
|
121 |
# 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
|
122 |
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
|
123 |
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
|
124 |
# 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
|
125 |
return html_escape(text_nohtml[:length] + u'...') |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
126 |
|
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
127 |
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
|
128 |
|
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
|
129 |
|
0 | 130 |
try: |
131 |
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
|
132 |
except (ImportError, AttributeError): |
0 | 133 |
# 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
|
134 |
pass |
0 | 135 |
else: |
136 |
||
137 |
def soup2xhtml(data, encoding): |
|
138 |
"""tidy (at least try) html soup and return the result |
|
139 |
Note: the function considers a string with no surrounding tag as valid |
|
140 |
if <div>`data`</div> can be parsed by an XML parser |
|
141 |
""" |
|
142 |
xmltree = etree.HTML('<div>%s</div>' % data) |
|
143 |
# NOTE: lxml 1.1 (etch platforms) doesn't recognize |
|
144 |
# the encoding=unicode parameter (lxml 2.0 does), this is |
|
145 |
# why we specify an encoding and re-decode to unicode later |
|
146 |
body = etree.tostring(xmltree[0], encoding=encoding) |
|
147 |
# remove <body> and </body> and decode to unicode |
|
148 |
return body[11:-13].decode(encoding) |
|
149 |
||
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
|
150 |
if hasattr(etree.HTML('<div>test</div>'), 'iter'): |
165 | 151 |
|
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
|
152 |
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
|
153 |
"""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
|
154 |
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
|
155 |
""" |
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
|
156 |
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
|
157 |
return u'' |
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
158 |
dom = etree.HTML(text) |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
159 |
curlength = 0 |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
160 |
add_ellipsis = False |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
161 |
for element in dom.iter(): |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
162 |
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
|
163 |
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
|
164 |
parent.remove(element) |
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
165 |
if curlength == length and (element.text or element.tail): |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
166 |
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
|
167 |
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
|
168 |
if element.text is not None: |
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
169 |
element.text = cut(element.text, length - curlength) |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
170 |
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
|
171 |
if element.tail is not None: |
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
172 |
if curlength < length: |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
173 |
element.tail = cut(element.tail, length - curlength) |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
174 |
curlength += len(element.tail) |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
175 |
elif curlength == length: |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
176 |
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
|
177 |
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
|
178 |
element.tail = '' |
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
179 |
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
|
180 |
if add_ellipsis: |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
181 |
return text + u'...' |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
182 |
return text |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
183 |
|
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
184 |
def text_cut(text, nbwords=30): |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
185 |
"""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
|
186 |
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
|
187 |
|
350
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
188 |
Note that spaces are normalized. |
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 |
if text is None: |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
191 |
return u'' |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
192 |
words = text.split() |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
193 |
text = ' '.join(words) # normalize spaces |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
194 |
minlength = len(' '.join(words[:nbwords])) |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
195 |
textlength = text.find('.', minlength) + 1 |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
196 |
if textlength == 0: # no point found |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
197 |
textlength = minlength |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
198 |
return text[:textlength] |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
199 |
|
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
200 |
def cut(text, length): |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
201 |
"""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
|
202 |
(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
|
203 |
resulting in a string of len <length> + 3) |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
204 |
""" |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
205 |
if text is None: |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
206 |
return u'' |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
207 |
if len(text) <= length: |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
208 |
return text |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
209 |
# 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
|
210 |
return text[:length] + u'...' |
f34ef2c64605
cleanup/fix cut variants
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
277
diff
changeset
|
211 |
|
165 | 212 |
|
0 | 213 |
|
214 |
# HTML generation helper functions ############################################ |
|
215 |
||
525
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
216 |
def simple_sgml_tag(tag, content=None, **attrs): |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
217 |
"""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
|
218 |
|
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
219 |
content and attributes will be escaped |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
220 |
""" |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
221 |
value = u'<%s' % tag |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
222 |
if attrs: |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
223 |
value += u' ' + u' '.join(u'%s="%s"' % (attr, html_escape(unicode(value))) |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
224 |
for attr, value in attrs.items()) |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
225 |
if content: |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
226 |
value += u'>%s</%s>' % (html_escape(unicode(content)), tag) |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
227 |
else: |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
228 |
value += u'/>' |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
229 |
return value |
bd4e03297cf0
function to make generation of a simple sgml tag
sylvain.thenault@logilab.fr
parents:
362
diff
changeset
|
230 |
|
0 | 231 |
def tooltipize(text, tooltip, url=None): |
232 |
"""make an HTML tooltip""" |
|
233 |
url = url or '#' |
|
234 |
return u'<a href="%s" title="%s">%s</a>' % (url, tooltip, text) |
|
235 |
||
236 |
def toggle_action(nodeid): |
|
237 |
"""builds a HTML link that uses the js toggleVisibility function""" |
|
238 |
return u"javascript: toggleVisibility('%s')" % nodeid |
|
239 |
||
240 |
def toggle_link(nodeid, label): |
|
241 |
"""builds a HTML link that uses the js toggleVisibility function""" |
|
242 |
return u'<a href="%s">%s</a>' % (toggle_action(nodeid), label) |
|
243 |
||
244 |
def ajax_replace_url(nodeid, rql, vid=None, swap=False, **extraparams): |
|
245 |
"""builds a replacePageChunk-like url |
|
246 |
>>> ajax_replace_url('foo', 'Person P') |
|
247 |
"javascript: replacePageChunk('foo', 'Person%20P');" |
|
248 |
>>> ajax_replace_url('foo', 'Person P', 'oneline') |
|
249 |
"javascript: replacePageChunk('foo', 'Person%20P', 'oneline');" |
|
250 |
>>> ajax_replace_url('foo', 'Person P', 'oneline', name='bar', age=12) |
|
251 |
"javascript: replacePageChunk('foo', 'Person%20P', 'oneline', {'age':12, 'name':'bar'});" |
|
252 |
>>> ajax_replace_url('foo', 'Person P', name='bar', age=12) |
|
253 |
"javascript: replacePageChunk('foo', 'Person%20P', 'null', {'age':12, 'name':'bar'});" |
|
254 |
""" |
|
255 |
params = [repr(nodeid), repr(urlquote(rql))] |
|
256 |
if extraparams and not vid: |
|
257 |
params.append("'null'") |
|
258 |
elif vid: |
|
259 |
params.append(repr(vid)) |
|
260 |
if extraparams: |
|
261 |
params.append(simplejson.dumps(extraparams)) |
|
262 |
if swap: |
|
263 |
params.append('true') |
|
264 |
return "javascript: replacePageChunk(%s);" % ', '.join(params) |
|
265 |
||
266 |
||
267 |
from StringIO import StringIO |
|
268 |
||
269 |
def ureport_as_html(layout): |
|
270 |
from logilab.common.ureports import HTMLWriter |
|
271 |
formater = HTMLWriter(True) |
|
272 |
stream = StringIO() #UStringIO() don't want unicode assertion |
|
273 |
formater.format(layout, stream) |
|
274 |
res = stream.getvalue() |
|
275 |
if isinstance(res, str): |
|
276 |
res = unicode(res, 'UTF8') |
|
277 |
return res |
|
278 |
||
279 |
def render_HTML_tree(tree, selected_node=None, render_node=None, caption=None): |
|
280 |
""" |
|
281 |
Generate a pure HTML representation of a tree given as an instance |
|
282 |
of a logilab.common.tree.Node |
|
283 |
||
284 |
selected_node is the currently selected node (if any) which will |
|
285 |
have its surrounding <div> have id="selected" (which default |
|
286 |
to a bold border libe with the default CSS). |
|
287 |
||
288 |
render_node is a function that should take a Node content (Node.id) |
|
289 |
as parameter and should return a string (what will be displayed |
|
290 |
in the cell). |
|
291 |
||
292 |
Warning: proper rendering of the generated html code depends on html_tree.css |
|
293 |
""" |
|
294 |
tree_depth = tree.depth_down() |
|
295 |
if render_node is None: |
|
296 |
render_node = str |
|
297 |
||
298 |
# helper function that build a matrix from the tree, like: |
|
299 |
# +------+-----------+-----------+ |
|
300 |
# | root | child_1_1 | child_2_1 | |
|
301 |
# | root | child_1_1 | child_2_2 | |
|
302 |
# | root | child_1_2 | | |
|
303 |
# | root | child_1_3 | child_2_3 | |
|
304 |
# | root | child_1_3 | child_2_4 | |
|
305 |
# +------+-----------+-----------+ |
|
306 |
# from: |
|
307 |
# root -+- child_1_1 -+- child_2_1 |
|
308 |
# | | |
|
309 |
# | +- child_2_2 |
|
310 |
# +- child_1_2 |
|
311 |
# | |
|
312 |
# +- child1_3 -+- child_2_3 |
|
313 |
# | |
|
314 |
# +- child_2_2 |
|
315 |
def build_matrix(path, matrix): |
|
316 |
if path[-1].is_leaf(): |
|
317 |
matrix.append(path[:]) |
|
318 |
else: |
|
319 |
for child in path[-1].children: |
|
320 |
build_matrix(path[:] + [child], matrix) |
|
321 |
||
322 |
matrix = [] |
|
323 |
build_matrix([tree], matrix) |
|
324 |
||
325 |
# make all lines in the matrix have the same number of columns |
|
326 |
for line in matrix: |
|
327 |
line.extend([None]*(tree_depth-len(line))) |
|
328 |
for i in range(len(matrix)-1, 0, -1): |
|
329 |
prev_line, line = matrix[i-1:i+1] |
|
330 |
for j in range(len(line)): |
|
331 |
if line[j] == prev_line[j]: |
|
332 |
line[j] = None |
|
333 |
||
334 |
# We build the matrix of link types (between 2 cells on a line of the matrix) |
|
335 |
# link types are : |
|
336 |
link_types = {(True, True, True ): 1, # T |
|
337 |
(False, False, True ): 2, # | |
|
338 |
(False, True, True ): 3, # + (actually, vert. bar with horiz. bar on the right) |
|
339 |
(False, True, False): 4, # L |
|
340 |
(True, True, False): 5, # - |
|
341 |
} |
|
342 |
links = [] |
|
343 |
for i, line in enumerate(matrix): |
|
344 |
links.append([]) |
|
345 |
for j in range(tree_depth-1): |
|
346 |
cell_11 = line[j] is not None |
|
347 |
cell_12 = line[j+1] is not None |
|
348 |
cell_21 = line[j+1] is not None and line[j+1].next_sibling() is not None |
|
349 |
link_type = link_types.get((cell_11, cell_12, cell_21), 0) |
|
350 |
if link_type == 0 and i > 0 and links[i-1][j] in (1,2,3): |
|
351 |
link_type = 2 |
|
352 |
links[-1].append(link_type) |
|
353 |
||
354 |
||
355 |
# We can now generate the HTML code for the <table> |
|
356 |
s = u'<table class="tree">\n' |
|
357 |
if caption: |
|
358 |
s += '<caption>%s</caption>\n' % caption |
|
359 |
||
360 |
for i, link_line in enumerate(links): |
|
361 |
line = matrix[i] |
|
362 |
||
363 |
s += '<tr>' |
|
364 |
for j, link_cell in enumerate(link_line): |
|
365 |
cell = line[j] |
|
366 |
if cell: |
|
367 |
if cell.id == selected_node: |
|
368 |
s += '<td class="tree_cell" rowspan="2"><div id="selected" class="tree_cell">%s</div></td>' % (render_node(cell.id)) |
|
369 |
else: |
|
370 |
s += '<td class="tree_cell" rowspan="2"><div class="tree_cell">%s</div></td>' % (render_node(cell.id)) |
|
371 |
else: |
|
372 |
s += '<td rowspan="2"> </td>' |
|
373 |
s += '<td class="tree_cell_%d_1"> </td>' % link_cell |
|
374 |
s += '<td class="tree_cell_%d_2"> </td>' % link_cell |
|
375 |
||
376 |
cell = line[-1] |
|
377 |
if cell: |
|
378 |
if cell.id == selected_node: |
|
379 |
s += '<td class="tree_cell" rowspan="2"><div id="selected" class="tree_cell">%s</div></td>' % (render_node(cell.id)) |
|
380 |
else: |
|
381 |
s += '<td class="tree_cell" rowspan="2"><div class="tree_cell">%s</div></td>' % (render_node(cell.id)) |
|
382 |
else: |
|
383 |
s += '<td rowspan="2"> </td>' |
|
384 |
||
385 |
s += '</tr>\n' |
|
386 |
if link_line: |
|
387 |
s += '<tr>' |
|
388 |
for j, link_cell in enumerate(link_line): |
|
389 |
s += '<td class="tree_cell_%d_3"> </td>' % link_cell |
|
390 |
s += '<td class="tree_cell_%d_4"> </td>' % link_cell |
|
391 |
s += '</tr>\n' |
|
392 |
||
393 |
s += '</table>' |
|
394 |
return s |
|
395 |
||
396 |
||
397 |
||
398 |
# traceback formatting ######################################################## |
|
399 |
||
400 |
import traceback |
|
401 |
||
402 |
def rest_traceback(info, exception): |
|
403 |
"""return a ReST formated traceback""" |
|
404 |
res = [u'Traceback\n---------\n::\n'] |
|
405 |
for stackentry in traceback.extract_tb(info[2]): |
|
406 |
res.append(u'\tFile %s, line %s, function %s' % tuple(stackentry[:3])) |
|
407 |
if stackentry[3]: |
|
408 |
res.append(u'\t %s' % stackentry[3].decode('utf-8', 'replace')) |
|
409 |
res.append(u'\n') |
|
410 |
try: |
|
411 |
res.append(u'\t Error: %s\n' % exception) |
|
412 |
except: |
|
413 |
pass |
|
414 |
return u'\n'.join(res) |
|
415 |
||
416 |
||
417 |
def html_traceback(info, exception, title='', |
|
418 |
encoding='ISO-8859-1', body=''): |
|
419 |
""" return an html formatted traceback from python exception infos. |
|
420 |
""" |
|
421 |
tcbk = info[2] |
|
422 |
stacktb = traceback.extract_tb(tcbk) |
|
423 |
strings = [] |
|
424 |
if body: |
|
425 |
strings.append(u'<div class="error_body">') |
|
426 |
# FIXME |
|
427 |
strings.append(body) |
|
428 |
strings.append(u'</div>') |
|
429 |
if title: |
|
430 |
strings.append(u'<h1 class="error">%s</h1>'% html_escape(title)) |
|
431 |
try: |
|
432 |
strings.append(u'<p class="error">%s</p>' % html_escape(str(exception)).replace("\n","<br />")) |
|
433 |
except UnicodeError: |
|
434 |
pass |
|
435 |
strings.append(u'<div class="error_traceback">') |
|
436 |
for index, stackentry in enumerate(stacktb): |
|
437 |
strings.append(u'<b>File</b> <b class="file">%s</b>, <b>line</b> ' |
|
438 |
u'<b class="line">%s</b>, <b>function</b> ' |
|
439 |
u'<b class="function">%s</b>:<br/>'%( |
|
440 |
html_escape(stackentry[0]), stackentry[1], html_escape(stackentry[2]))) |
|
441 |
if stackentry[3]: |
|
442 |
string = html_escape(stackentry[3]).decode('utf-8', 'replace') |
|
443 |
strings.append(u' %s<br/>\n' % (string)) |
|
444 |
# add locals info for each entry |
|
445 |
try: |
|
446 |
local_context = tcbk.tb_frame.f_locals |
|
447 |
html_info = [] |
|
448 |
chars = 0 |
|
449 |
for name, value in local_context.iteritems(): |
|
450 |
value = html_escape(repr(value)) |
|
451 |
info = u'<span class="name">%s</span>=%s, ' % (name, value) |
|
452 |
line_length = len(name) + len(value) |
|
453 |
chars += line_length |
|
454 |
# 150 is the result of *years* of research ;-) (CSS might be helpful here) |
|
455 |
if chars > 150: |
|
456 |
info = u'<br/>' + info |
|
457 |
chars = line_length |
|
458 |
html_info.append(info) |
|
459 |
boxid = 'ctxlevel%d' % index |
|
460 |
strings.append(u'[%s]' % toggle_link(boxid, '+')) |
|
461 |
strings.append(u'<div id="%s" class="pycontext hidden">%s</div>' % |
|
462 |
(boxid, ''.join(html_info))) |
|
463 |
tcbk = tcbk.tb_next |
|
464 |
except Exception: |
|
465 |
pass # doesn't really matter if we have no context info |
|
466 |
strings.append(u'</div>') |
|
467 |
return '\n'.join(strings) |
|
468 |
||
469 |
# csv files / unicode support ################################################# |
|
470 |
||
471 |
class UnicodeCSVWriter: |
|
472 |
"""proxies calls to csv.writer.writerow to be able to deal with unicode""" |
|
473 |
||
474 |
def __init__(self, wfunc, encoding, **kwargs): |
|
475 |
self.writer = csv.writer(self, **kwargs) |
|
476 |
self.wfunc = wfunc |
|
477 |
self.encoding = encoding |
|
478 |
||
479 |
def write(self, data): |
|
480 |
self.wfunc(data) |
|
481 |
||
482 |
def writerow(self, row): |
|
483 |
csvrow = [] |
|
484 |
for elt in row: |
|
485 |
if isinstance(elt, unicode): |
|
486 |
csvrow.append(elt.encode(self.encoding)) |
|
487 |
else: |
|
488 |
csvrow.append(str(elt)) |
|
489 |
self.writer.writerow(csvrow) |
|
490 |
||
491 |
def writerows(self, rows): |
|
492 |
for row in rows: |
|
493 |
self.writerow(row) |
|
494 |
||
495 |
||
496 |
# some decorators ############################################################# |
|
497 |
||
498 |
class limitsize(object): |
|
499 |
def __init__(self, maxsize): |
|
500 |
self.maxsize = maxsize |
|
501 |
||
502 |
def __call__(self, function): |
|
503 |
def newfunc(*args, **kwargs): |
|
504 |
ret = function(*args, **kwargs) |
|
505 |
if isinstance(ret, basestring): |
|
506 |
return ret[:self.maxsize] |
|
507 |
return ret |
|
508 |
return newfunc |
|
509 |
||
510 |
||
511 |
def jsonize(function): |
|
512 |
import simplejson |
|
513 |
def newfunc(*args, **kwargs): |
|
514 |
ret = function(*args, **kwargs) |
|
515 |
if isinstance(ret, decimal.Decimal): |
|
516 |
ret = float(ret) |
|
517 |
elif isinstance(ret, DateTimeType): |
|
518 |
ret = ret.strftime('%Y-%m-%d %H:%M') |
|
519 |
elif isinstance(ret, DateTimeDeltaType): |
|
520 |
ret = ret.seconds |
|
521 |
try: |
|
522 |
return simplejson.dumps(ret) |
|
523 |
except TypeError: |
|
524 |
return simplejson.dumps(repr(ret)) |
|
525 |
return newfunc |
|
526 |
||
527 |
||
528 |
def htmlescape(function): |
|
529 |
def newfunc(*args, **kwargs): |
|
530 |
ret = function(*args, **kwargs) |
|
531 |
assert isinstance(ret, basestring) |
|
532 |
return html_escape(ret) |
|
533 |
return newfunc |