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