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