2013-10-04 11:41:55 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
2014-01-16 18:27:50 +00:00
|
|
|
import collections
|
2013-10-07 09:15:56 +00:00
|
|
|
import cStringIO
|
2013-10-14 08:52:15 +00:00
|
|
|
import datetime
|
2014-04-10 15:54:12 +00:00
|
|
|
import hashlib
|
2013-11-28 15:36:30 +00:00
|
|
|
import json
|
2014-07-02 14:01:36 +00:00
|
|
|
import itertools
|
2013-06-27 15:08:07 +00:00
|
|
|
import logging
|
2013-11-28 15:36:30 +00:00
|
|
|
import math
|
2014-04-09 16:17:58 +00:00
|
|
|
import os
|
2013-08-08 18:11:38 +00:00
|
|
|
import re
|
2014-01-27 11:39:21 +00:00
|
|
|
import sys
|
2014-06-26 14:49:51 +00:00
|
|
|
import textwrap
|
|
|
|
import uuid
|
|
|
|
from subprocess import Popen, PIPE
|
2014-04-09 16:17:58 +00:00
|
|
|
from urlparse import urlparse
|
2013-06-27 14:20:22 +00:00
|
|
|
|
2013-11-28 15:36:30 +00:00
|
|
|
import babel
|
|
|
|
import babel.dates
|
2014-07-02 14:01:36 +00:00
|
|
|
import werkzeug
|
|
|
|
from lxml import etree, html
|
2014-01-14 12:48:43 +00:00
|
|
|
from PIL import Image
|
2015-07-08 17:19:28 +00:00
|
|
|
import psycopg2
|
2013-06-27 15:08:07 +00:00
|
|
|
|
2014-04-08 07:52:05 +00:00
|
|
|
import openerp.http
|
2013-10-21 15:26:39 +00:00
|
|
|
import openerp.tools
|
2014-06-19 16:09:01 +00:00
|
|
|
from openerp.tools.func import lazy_property
|
2014-04-18 13:29:29 +00:00
|
|
|
import openerp.tools.lru
|
2014-05-05 16:09:53 +00:00
|
|
|
from openerp.http import request
|
2014-01-16 18:27:50 +00:00
|
|
|
from openerp.tools.safe_eval import safe_eval as eval
|
2013-11-28 15:36:30 +00:00
|
|
|
from openerp.osv import osv, orm, fields
|
2014-06-10 16:46:40 +00:00
|
|
|
from openerp.tools import html_escape as escape
|
2013-11-28 15:36:30 +00:00
|
|
|
from openerp.tools.translate import _
|
2013-06-27 15:08:07 +00:00
|
|
|
|
|
|
|
_logger = logging.getLogger(__name__)
|
2013-06-27 09:13:29 +00:00
|
|
|
|
2015-04-01 22:55:26 +00:00
|
|
|
MAX_CSS_RULES = 4095
|
|
|
|
|
2014-01-19 17:44:37 +00:00
|
|
|
#--------------------------------------------------------------------
|
|
|
|
# QWeb template engine
|
|
|
|
#--------------------------------------------------------------------
|
2013-10-18 09:59:13 +00:00
|
|
|
class QWebException(Exception):
|
2014-01-31 11:35:15 +00:00
|
|
|
def __init__(self, message, **kw):
|
2014-01-27 14:57:28 +00:00
|
|
|
Exception.__init__(self, message)
|
2014-01-31 11:35:15 +00:00
|
|
|
self.qweb = dict(kw)
|
2014-07-14 11:42:29 +00:00
|
|
|
def pretty_xml(self):
|
|
|
|
if 'node' not in self.qweb:
|
|
|
|
return ''
|
|
|
|
return etree.tostring(self.qweb['node'], pretty_print=True)
|
2014-01-27 11:39:21 +00:00
|
|
|
|
|
|
|
class QWebTemplateNotFound(QWebException):
|
|
|
|
pass
|
2013-10-18 09:59:13 +00:00
|
|
|
|
2014-03-05 11:04:35 +00:00
|
|
|
def raise_qweb_exception(etype=None, **kw):
|
2014-01-31 11:35:15 +00:00
|
|
|
if etype is None:
|
|
|
|
etype = QWebException
|
|
|
|
orig_type, original, tb = sys.exc_info()
|
|
|
|
try:
|
|
|
|
raise etype, original, tb
|
|
|
|
except etype, e:
|
|
|
|
for k, v in kw.items():
|
|
|
|
e.qweb[k] = v
|
|
|
|
# Will use `raise foo from bar` in python 3 and rename cause to __cause__
|
|
|
|
e.qweb['cause'] = original
|
2014-03-05 11:04:35 +00:00
|
|
|
raise
|
2014-01-31 11:35:15 +00:00
|
|
|
|
2015-02-27 13:45:48 +00:00
|
|
|
def _build_attribute(name, value):
|
|
|
|
value = escape(value)
|
|
|
|
if isinstance(name, unicode): name = name.encode('utf-8')
|
|
|
|
if isinstance(value, unicode): value = value.encode('utf-8')
|
|
|
|
return ' %s="%s"' % (name, value)
|
|
|
|
|
2013-08-08 18:11:38 +00:00
|
|
|
class QWebContext(dict):
|
2014-01-16 18:27:50 +00:00
|
|
|
def __init__(self, cr, uid, data, loader=None, templates=None, context=None):
|
2013-10-18 14:45:46 +00:00
|
|
|
self.cr = cr
|
|
|
|
self.uid = uid
|
2013-10-04 11:41:55 +00:00
|
|
|
self.loader = loader
|
2013-10-15 15:28:58 +00:00
|
|
|
self.templates = templates or {}
|
2013-10-18 14:45:46 +00:00
|
|
|
self.context = context
|
2014-01-16 18:27:50 +00:00
|
|
|
dic = dict(data)
|
2013-09-25 12:10:28 +00:00
|
|
|
super(QWebContext, self).__init__(dic)
|
2013-08-08 18:11:38 +00:00
|
|
|
self['defined'] = lambda key: key in self
|
|
|
|
|
2013-10-14 08:52:15 +00:00
|
|
|
def safe_eval(self, expr):
|
2014-01-16 18:27:50 +00:00
|
|
|
locals_dict = collections.defaultdict(lambda: None)
|
|
|
|
locals_dict.update(self)
|
|
|
|
locals_dict.pop('cr', None)
|
|
|
|
locals_dict.pop('loader', None)
|
|
|
|
return eval(expr, None, locals_dict, nocopy=True, locals_builtins=True)
|
2013-10-14 08:52:15 +00:00
|
|
|
|
2013-10-04 11:41:55 +00:00
|
|
|
def copy(self):
|
2014-09-11 13:52:38 +00:00
|
|
|
""" Clones the current context, conserving all data and metadata
|
|
|
|
(loader, template cache, ...)
|
|
|
|
"""
|
2013-10-18 14:45:46 +00:00
|
|
|
return QWebContext(self.cr, self.uid, dict.copy(self),
|
2013-10-15 15:28:58 +00:00
|
|
|
loader=self.loader,
|
2013-10-18 14:45:46 +00:00
|
|
|
templates=self.templates,
|
|
|
|
context=self.context)
|
2013-10-04 11:41:55 +00:00
|
|
|
|
|
|
|
def __copy__(self):
|
|
|
|
return self.copy()
|
|
|
|
|
|
|
|
class QWeb(orm.AbstractModel):
|
2014-09-11 13:52:38 +00:00
|
|
|
""" Base QWeb rendering engine
|
2013-10-08 07:07:42 +00:00
|
|
|
|
2014-09-11 13:52:38 +00:00
|
|
|
* to customize ``t-field`` rendering, subclass ``ir.qweb.field`` and
|
|
|
|
create new models called :samp:`ir.qweb.field.{widget}`
|
|
|
|
* alternatively, override :meth:`~.get_converter_for` and return an
|
|
|
|
arbitrary model to use as field converter
|
2014-01-19 17:44:37 +00:00
|
|
|
|
|
|
|
Beware that if you need extensions or alterations which could be
|
|
|
|
incompatible with other subsystems, you should create a local object
|
|
|
|
inheriting from ``ir.qweb`` and customize that.
|
2013-06-27 09:13:29 +00:00
|
|
|
"""
|
2013-10-04 11:41:55 +00:00
|
|
|
|
2013-10-07 09:15:56 +00:00
|
|
|
_name = 'ir.qweb'
|
2013-10-04 11:41:55 +00:00
|
|
|
|
|
|
|
_void_elements = frozenset([
|
2015-11-19 13:59:44 +00:00
|
|
|
u'area', u'base', u'br', u'col', u'embed', u'hr', u'img', u'input',
|
|
|
|
u'keygen', u'link', u'menuitem', u'meta', u'param', u'source',
|
|
|
|
u'track', u'wbr'])
|
2013-10-04 12:52:04 +00:00
|
|
|
_format_regex = re.compile(
|
|
|
|
'(?:'
|
|
|
|
# ruby-style pattern
|
|
|
|
'#\{(.+?)\}'
|
|
|
|
')|(?:'
|
|
|
|
# jinja-style pattern
|
|
|
|
'\{\{(.+?)\}\}'
|
|
|
|
')')
|
2013-10-04 11:41:55 +00:00
|
|
|
|
|
|
|
def __init__(self, pool, cr):
|
|
|
|
super(QWeb, self).__init__(pool, cr)
|
|
|
|
|
|
|
|
self._render_tag = self.prefixed_methods('render_tag_')
|
|
|
|
self._render_att = self.prefixed_methods('render_att_')
|
|
|
|
|
|
|
|
def prefixed_methods(self, prefix):
|
|
|
|
""" Extracts all methods prefixed by ``prefix``, and returns a mapping
|
|
|
|
of (t-name, method) where the t-name is the method name with prefix
|
|
|
|
removed and underscore converted to dashes
|
|
|
|
|
|
|
|
:param str prefix:
|
|
|
|
:return: dict
|
|
|
|
"""
|
2014-01-23 12:46:51 +00:00
|
|
|
n_prefix = len(prefix)
|
2013-10-04 11:41:55 +00:00
|
|
|
return dict(
|
2014-01-23 12:46:51 +00:00
|
|
|
(name[n_prefix:].replace('_', '-'), getattr(type(self), name))
|
2013-10-04 11:41:55 +00:00
|
|
|
for name in dir(self)
|
2014-01-23 12:46:51 +00:00
|
|
|
if name.startswith(prefix)
|
|
|
|
)
|
2013-06-27 15:08:07 +00:00
|
|
|
|
|
|
|
def register_tag(self, tag, func):
|
|
|
|
self._render_tag[tag] = func
|
|
|
|
|
2014-01-28 20:12:35 +00:00
|
|
|
def add_template(self, qwebcontext, name, node):
|
|
|
|
"""Add a parsed template in the context. Used to preprocess templates."""
|
|
|
|
qwebcontext.templates[name] = node
|
|
|
|
|
2014-04-09 12:46:26 +00:00
|
|
|
def load_document(self, document, res_id, qwebcontext):
|
2013-10-04 11:41:55 +00:00
|
|
|
"""
|
|
|
|
Loads an XML document and installs any contained template in the engine
|
2014-09-11 13:52:38 +00:00
|
|
|
|
|
|
|
:type document: a parsed lxml.etree element, an unparsed XML document
|
|
|
|
(as a string) or the path of an XML file to load
|
2013-10-04 11:41:55 +00:00
|
|
|
"""
|
2014-09-11 06:15:46 +00:00
|
|
|
if not isinstance(document, basestring):
|
|
|
|
# assume lxml.etree.Element
|
2014-01-23 12:46:51 +00:00
|
|
|
dom = document
|
|
|
|
elif document.startswith("<?xml"):
|
2014-07-02 14:01:36 +00:00
|
|
|
dom = etree.fromstring(document)
|
2013-06-27 09:13:29 +00:00
|
|
|
else:
|
2014-09-11 06:15:46 +00:00
|
|
|
dom = etree.parse(document).getroot()
|
2013-10-04 11:41:55 +00:00
|
|
|
|
2014-07-02 14:01:36 +00:00
|
|
|
for node in dom:
|
|
|
|
if node.get('t-name'):
|
|
|
|
name = str(node.get("t-name"))
|
|
|
|
self.add_template(qwebcontext, name, node)
|
|
|
|
if res_id and node.tag == "t":
|
|
|
|
self.add_template(qwebcontext, res_id, node)
|
|
|
|
res_id = None
|
2013-11-12 14:08:22 +00:00
|
|
|
|
2014-01-28 20:12:35 +00:00
|
|
|
def get_template(self, name, qwebcontext):
|
2014-09-11 13:52:38 +00:00
|
|
|
""" Tries to fetch the template ``name``, either gets it from the
|
|
|
|
context's template cache or loads one with the context's loader (if
|
|
|
|
any).
|
|
|
|
|
|
|
|
:raises QWebTemplateNotFound: if the template can not be found or loaded
|
|
|
|
"""
|
2014-01-28 20:12:35 +00:00
|
|
|
origin_template = qwebcontext.get('__caller__') or qwebcontext['__stack__'][0]
|
|
|
|
if qwebcontext.loader and name not in qwebcontext.templates:
|
2014-01-27 11:39:21 +00:00
|
|
|
try:
|
2014-01-28 20:12:35 +00:00
|
|
|
xml_doc = qwebcontext.loader(name)
|
2014-01-31 11:35:15 +00:00
|
|
|
except ValueError:
|
2014-03-05 11:04:35 +00:00
|
|
|
raise_qweb_exception(QWebTemplateNotFound, message="Loader could not find template %r" % name, template=origin_template)
|
2014-04-09 12:46:26 +00:00
|
|
|
self.load_document(xml_doc, isinstance(name, (int, long)) and name or None, qwebcontext=qwebcontext)
|
2013-06-27 14:20:22 +00:00
|
|
|
|
2014-01-28 20:12:35 +00:00
|
|
|
if name in qwebcontext.templates:
|
|
|
|
return qwebcontext.templates[name]
|
2013-10-04 11:41:55 +00:00
|
|
|
|
2014-01-31 01:08:02 +00:00
|
|
|
raise QWebTemplateNotFound("Template %r not found" % name, template=origin_template)
|
2013-10-04 11:41:55 +00:00
|
|
|
|
2014-01-23 12:46:51 +00:00
|
|
|
def eval(self, expr, qwebcontext):
|
2013-08-08 18:11:38 +00:00
|
|
|
try:
|
2014-01-23 12:46:51 +00:00
|
|
|
return qwebcontext.safe_eval(expr)
|
2014-01-31 11:35:15 +00:00
|
|
|
except Exception:
|
2014-01-27 11:39:21 +00:00
|
|
|
template = qwebcontext.get('__template__')
|
2014-03-05 11:04:35 +00:00
|
|
|
raise_qweb_exception(message="Could not evaluate expression %r" % expr, expression=expr, template=template)
|
2013-08-08 18:11:38 +00:00
|
|
|
|
2014-01-23 12:46:51 +00:00
|
|
|
def eval_object(self, expr, qwebcontext):
|
|
|
|
return self.eval(expr, qwebcontext)
|
2013-06-27 15:08:07 +00:00
|
|
|
|
2014-01-23 12:46:51 +00:00
|
|
|
def eval_str(self, expr, qwebcontext):
|
2013-08-08 18:11:38 +00:00
|
|
|
if expr == "0":
|
2014-01-23 12:46:51 +00:00
|
|
|
return qwebcontext.get(0, '')
|
|
|
|
val = self.eval(expr, qwebcontext)
|
2013-08-08 18:11:38 +00:00
|
|
|
if isinstance(val, unicode):
|
|
|
|
return val.encode("utf8")
|
2014-01-29 18:06:00 +00:00
|
|
|
if val is False or val is None:
|
|
|
|
return ''
|
2013-08-08 18:11:38 +00:00
|
|
|
return str(val)
|
2013-06-27 15:08:07 +00:00
|
|
|
|
2014-01-23 12:46:51 +00:00
|
|
|
def eval_format(self, expr, qwebcontext):
|
2013-10-04 12:52:04 +00:00
|
|
|
expr, replacements = self._format_regex.subn(
|
2014-01-23 12:46:51 +00:00
|
|
|
lambda m: self.eval_str(m.group(1) or m.group(2), qwebcontext),
|
|
|
|
expr
|
|
|
|
)
|
2013-09-24 08:46:20 +00:00
|
|
|
|
2013-10-04 12:52:04 +00:00
|
|
|
if replacements:
|
2013-08-08 18:11:38 +00:00
|
|
|
return expr
|
2013-10-04 12:52:04 +00:00
|
|
|
|
|
|
|
try:
|
2014-01-23 12:46:51 +00:00
|
|
|
return str(expr % qwebcontext)
|
2014-01-31 11:35:15 +00:00
|
|
|
except Exception:
|
2014-01-27 11:39:21 +00:00
|
|
|
template = qwebcontext.get('__template__')
|
2014-03-05 11:04:35 +00:00
|
|
|
raise_qweb_exception(message="Format error for expression %r" % expr, expression=expr, template=template)
|
2013-06-27 15:08:07 +00:00
|
|
|
|
2014-01-23 12:46:51 +00:00
|
|
|
def eval_bool(self, expr, qwebcontext):
|
|
|
|
return int(bool(self.eval(expr, qwebcontext)))
|
|
|
|
|
|
|
|
def render(self, cr, uid, id_or_xml_id, qwebcontext=None, loader=None, context=None):
|
2014-09-11 13:52:38 +00:00
|
|
|
""" render(cr, uid, id_or_xml_id, qwebcontext=None, loader=None, context=None)
|
|
|
|
|
|
|
|
Renders the template specified by the provided template name
|
|
|
|
|
|
|
|
:param qwebcontext: context for rendering the template
|
|
|
|
:type qwebcontext: dict or :class:`QWebContext` instance
|
|
|
|
:param loader: if ``qwebcontext`` is a dict, loader set into the
|
|
|
|
context instantiated for rendering
|
|
|
|
"""
|
2014-01-23 12:46:51 +00:00
|
|
|
if qwebcontext is None:
|
|
|
|
qwebcontext = {}
|
|
|
|
|
|
|
|
if not isinstance(qwebcontext, QWebContext):
|
|
|
|
qwebcontext = QWebContext(cr, uid, qwebcontext, loader=loader, context=context)
|
|
|
|
|
|
|
|
qwebcontext['__template__'] = id_or_xml_id
|
|
|
|
stack = qwebcontext.get('__stack__', [])
|
2013-08-12 10:52:11 +00:00
|
|
|
if stack:
|
2014-01-23 12:46:51 +00:00
|
|
|
qwebcontext['__caller__'] = stack[-1]
|
2014-01-19 17:44:37 +00:00
|
|
|
stack.append(id_or_xml_id)
|
2014-01-23 12:46:51 +00:00
|
|
|
qwebcontext['__stack__'] = stack
|
|
|
|
qwebcontext['xmlid'] = str(stack[0]) # Temporary fix
|
|
|
|
return self.render_node(self.get_template(id_or_xml_id, qwebcontext), qwebcontext)
|
|
|
|
|
|
|
|
def render_node(self, element, qwebcontext):
|
2014-07-02 14:01:36 +00:00
|
|
|
generated_attributes = ""
|
|
|
|
t_render = None
|
|
|
|
template_attributes = {}
|
|
|
|
for (attribute_name, attribute_value) in element.attrib.iteritems():
|
2015-11-19 13:59:44 +00:00
|
|
|
attribute_name = unicode(attribute_name)
|
2014-07-02 14:01:36 +00:00
|
|
|
if attribute_name == "groups":
|
|
|
|
cr = qwebcontext.get('request') and qwebcontext['request'].cr or None
|
|
|
|
uid = qwebcontext.get('request') and qwebcontext['request'].uid or None
|
|
|
|
can_see = self.user_has_groups(cr, uid, groups=attribute_value) if cr and uid else False
|
|
|
|
if not can_see:
|
|
|
|
return ''
|
|
|
|
|
|
|
|
attribute_value = attribute_value.encode("utf8")
|
|
|
|
|
|
|
|
if attribute_name.startswith("t-"):
|
|
|
|
for attribute in self._render_att:
|
|
|
|
if attribute_name[2:].startswith(attribute):
|
2014-09-11 06:38:08 +00:00
|
|
|
attrs = self._render_att[attribute](
|
|
|
|
self, element, attribute_name, attribute_value, qwebcontext)
|
|
|
|
for att, val in attrs:
|
|
|
|
if not val: continue
|
2014-09-11 10:54:20 +00:00
|
|
|
generated_attributes += self.render_attribute(element, att, val, qwebcontext)
|
2014-07-02 14:01:36 +00:00
|
|
|
break
|
|
|
|
else:
|
|
|
|
if attribute_name[2:] in self._render_tag:
|
|
|
|
t_render = attribute_name[2:]
|
|
|
|
template_attributes[attribute_name[2:]] = attribute_value
|
2013-06-27 09:13:29 +00:00
|
|
|
else:
|
2014-09-16 18:20:39 +00:00
|
|
|
generated_attributes += self.render_attribute(element, attribute_name, attribute_value, qwebcontext)
|
2014-07-02 14:01:36 +00:00
|
|
|
|
|
|
|
if 'debug' in template_attributes:
|
|
|
|
debugger = template_attributes.get('debug', 'pdb')
|
|
|
|
__import__(debugger).set_trace() # pdb, ipdb, pudb, ...
|
|
|
|
if t_render:
|
|
|
|
result = self._render_tag[t_render](self, element, template_attributes, generated_attributes, qwebcontext)
|
|
|
|
else:
|
|
|
|
result = self.render_element(element, template_attributes, generated_attributes, qwebcontext)
|
|
|
|
|
|
|
|
if element.tail:
|
2014-07-10 14:47:06 +00:00
|
|
|
result += element.tail.encode('utf-8')
|
2014-07-02 14:01:36 +00:00
|
|
|
|
2014-01-23 12:46:51 +00:00
|
|
|
if isinstance(result, unicode):
|
|
|
|
return result.encode('utf-8')
|
|
|
|
return result
|
|
|
|
|
|
|
|
def render_element(self, element, template_attributes, generated_attributes, qwebcontext, inner=None):
|
|
|
|
# element: element
|
|
|
|
# template_attributes: t-* attributes
|
|
|
|
# generated_attributes: generated attributes
|
|
|
|
# qwebcontext: values
|
2013-06-30 21:35:15 +00:00
|
|
|
# inner: optional innerXml
|
|
|
|
if inner:
|
2014-07-14 11:42:35 +00:00
|
|
|
g_inner = inner.encode('utf-8') if isinstance(inner, unicode) else inner
|
2013-06-30 21:35:15 +00:00
|
|
|
else:
|
2014-07-14 11:42:35 +00:00
|
|
|
g_inner = [] if element.text is None else [element.text.encode('utf-8')]
|
2014-07-02 16:00:03 +00:00
|
|
|
for current_node in element.iterchildren(tag=etree.Element):
|
2013-10-18 09:59:13 +00:00
|
|
|
try:
|
2014-01-23 12:46:51 +00:00
|
|
|
g_inner.append(self.render_node(current_node, qwebcontext))
|
2014-09-08 09:14:44 +00:00
|
|
|
except QWebException:
|
2013-11-02 16:55:15 +00:00
|
|
|
raise
|
2014-01-31 11:35:15 +00:00
|
|
|
except Exception:
|
2014-01-27 11:39:21 +00:00
|
|
|
template = qwebcontext.get('__template__')
|
2014-07-02 14:01:36 +00:00
|
|
|
raise_qweb_exception(message="Could not render element %r" % element.tag, node=element, template=template)
|
2015-11-19 13:59:44 +00:00
|
|
|
name = unicode(element.tag)
|
2013-06-27 15:08:07 +00:00
|
|
|
inner = "".join(g_inner)
|
2014-01-23 12:46:51 +00:00
|
|
|
trim = template_attributes.get("trim", 0)
|
2013-06-27 15:08:07 +00:00
|
|
|
if trim == 0:
|
2013-06-27 09:13:29 +00:00
|
|
|
pass
|
2013-06-27 15:08:07 +00:00
|
|
|
elif trim == 'left':
|
|
|
|
inner = inner.lstrip()
|
|
|
|
elif trim == 'right':
|
|
|
|
inner = inner.rstrip()
|
|
|
|
elif trim == 'both':
|
|
|
|
inner = inner.strip()
|
|
|
|
if name == "t":
|
2013-06-27 09:13:29 +00:00
|
|
|
return inner
|
2013-08-05 13:06:05 +00:00
|
|
|
elif len(inner) or name not in self._void_elements:
|
2013-09-27 12:10:12 +00:00
|
|
|
return "<%s%s>%s</%s>" % tuple(
|
2014-01-23 12:46:51 +00:00
|
|
|
qwebcontext if isinstance(qwebcontext, str) else qwebcontext.encode('utf-8')
|
|
|
|
for qwebcontext in (name, generated_attributes, inner, name)
|
|
|
|
)
|
2013-06-27 09:13:29 +00:00
|
|
|
else:
|
2015-11-19 13:59:44 +00:00
|
|
|
return "<%s%s/>" % (name.encode("utf-8"), generated_attributes)
|
2013-06-27 09:13:29 +00:00
|
|
|
|
2014-09-11 10:54:20 +00:00
|
|
|
def render_attribute(self, element, name, value, qwebcontext):
|
2015-02-27 13:45:48 +00:00
|
|
|
return _build_attribute(name, value)
|
2014-09-11 10:54:20 +00:00
|
|
|
|
2013-06-27 09:13:29 +00:00
|
|
|
# Attributes
|
2014-01-23 12:46:51 +00:00
|
|
|
def render_att_att(self, element, attribute_name, attribute_value, qwebcontext):
|
|
|
|
if attribute_name.startswith("t-attf-"):
|
2014-09-11 06:38:08 +00:00
|
|
|
return [(attribute_name[7:], self.eval_format(attribute_value, qwebcontext))]
|
|
|
|
|
|
|
|
if attribute_name.startswith("t-att-"):
|
|
|
|
return [(attribute_name[6:], self.eval(attribute_value, qwebcontext))]
|
|
|
|
|
|
|
|
result = self.eval_object(attribute_value, qwebcontext)
|
|
|
|
if isinstance(result, collections.Mapping):
|
|
|
|
return result.iteritems()
|
|
|
|
# assume tuple
|
|
|
|
return [result]
|
2013-09-24 08:46:20 +00:00
|
|
|
|
2013-06-27 09:13:29 +00:00
|
|
|
# Tags
|
2014-01-23 12:46:51 +00:00
|
|
|
def render_tag_raw(self, element, template_attributes, generated_attributes, qwebcontext):
|
|
|
|
inner = self.eval_str(template_attributes["raw"], qwebcontext)
|
|
|
|
return self.render_element(element, template_attributes, generated_attributes, qwebcontext, inner)
|
2013-06-27 15:08:07 +00:00
|
|
|
|
2014-01-23 12:46:51 +00:00
|
|
|
def render_tag_esc(self, element, template_attributes, generated_attributes, qwebcontext):
|
2014-04-07 13:11:45 +00:00
|
|
|
options = json.loads(template_attributes.get('esc-options') or '{}')
|
2014-08-05 15:19:36 +00:00
|
|
|
widget = self.get_widget_for(options.get('widget'))
|
2014-04-07 13:11:45 +00:00
|
|
|
inner = widget.format(template_attributes['esc'], options, qwebcontext)
|
2014-01-23 12:46:51 +00:00
|
|
|
return self.render_element(element, template_attributes, generated_attributes, qwebcontext, inner)
|
2013-06-27 15:08:07 +00:00
|
|
|
|
2014-09-11 09:23:13 +00:00
|
|
|
def _iterate(self, iterable):
|
|
|
|
if isinstance (iterable, collections.Mapping):
|
|
|
|
return iterable.iteritems()
|
|
|
|
|
|
|
|
return itertools.izip(*itertools.tee(iterable))
|
|
|
|
|
2014-01-23 12:46:51 +00:00
|
|
|
def render_tag_foreach(self, element, template_attributes, generated_attributes, qwebcontext):
|
|
|
|
expr = template_attributes["foreach"]
|
|
|
|
enum = self.eval_object(expr, qwebcontext)
|
2014-06-05 10:05:24 +00:00
|
|
|
if enum is None:
|
2014-01-23 12:46:51 +00:00
|
|
|
template = qwebcontext.get('__template__')
|
2014-01-27 11:39:21 +00:00
|
|
|
raise QWebException("foreach enumerator %r is not defined while rendering template %r" % (expr, template), template=template)
|
2014-09-11 09:23:13 +00:00
|
|
|
if isinstance(enum, int):
|
|
|
|
enum = range(enum)
|
2014-01-23 12:46:51 +00:00
|
|
|
|
2014-06-05 10:05:24 +00:00
|
|
|
varname = template_attributes['as'].replace('.', '_')
|
|
|
|
copy_qwebcontext = qwebcontext.copy()
|
2014-09-11 09:23:13 +00:00
|
|
|
|
|
|
|
size = None
|
2014-06-05 10:05:24 +00:00
|
|
|
if isinstance(enum, collections.Sized):
|
|
|
|
size = len(enum)
|
2014-09-11 09:23:13 +00:00
|
|
|
copy_qwebcontext["%s_size" % varname] = size
|
|
|
|
|
2014-06-05 10:05:24 +00:00
|
|
|
copy_qwebcontext["%s_all" % varname] = enum
|
|
|
|
ru = []
|
2014-09-11 09:23:13 +00:00
|
|
|
for index, (item, value) in enumerate(self._iterate(enum)):
|
2014-06-05 10:05:24 +00:00
|
|
|
copy_qwebcontext.update({
|
|
|
|
varname: item,
|
2014-09-11 09:23:13 +00:00
|
|
|
'%s_value' % varname: value,
|
2014-06-05 10:05:24 +00:00
|
|
|
'%s_index' % varname: index,
|
|
|
|
'%s_first' % varname: index == 0,
|
|
|
|
})
|
2014-09-11 09:23:13 +00:00
|
|
|
if size is not None:
|
|
|
|
copy_qwebcontext['%s_last' % varname] = index + 1 == size
|
2014-06-05 10:05:24 +00:00
|
|
|
if index % 2:
|
|
|
|
copy_qwebcontext.update({
|
|
|
|
'%s_parity' % varname: 'odd',
|
|
|
|
'%s_even' % varname: False,
|
|
|
|
'%s_odd' % varname: True,
|
|
|
|
})
|
|
|
|
else:
|
|
|
|
copy_qwebcontext.update({
|
|
|
|
'%s_parity' % varname: 'even',
|
|
|
|
'%s_even' % varname: True,
|
|
|
|
'%s_odd' % varname: False,
|
|
|
|
})
|
|
|
|
ru.append(self.render_element(element, template_attributes, generated_attributes, copy_qwebcontext))
|
2015-01-30 13:03:10 +00:00
|
|
|
|
|
|
|
for k in qwebcontext.keys():
|
|
|
|
qwebcontext[k] = copy_qwebcontext[k]
|
|
|
|
|
2014-06-05 10:05:24 +00:00
|
|
|
return "".join(ru)
|
|
|
|
|
2014-01-23 12:46:51 +00:00
|
|
|
def render_tag_if(self, element, template_attributes, generated_attributes, qwebcontext):
|
|
|
|
if self.eval_bool(template_attributes["if"], qwebcontext):
|
|
|
|
return self.render_element(element, template_attributes, generated_attributes, qwebcontext)
|
|
|
|
return ""
|
2013-06-27 15:08:07 +00:00
|
|
|
|
2014-01-23 12:46:51 +00:00
|
|
|
def render_tag_call(self, element, template_attributes, generated_attributes, qwebcontext):
|
|
|
|
d = qwebcontext.copy()
|
|
|
|
d[0] = self.render_element(element, template_attributes, generated_attributes, d)
|
2014-01-29 17:11:38 +00:00
|
|
|
cr = d.get('request') and d['request'].cr or None
|
|
|
|
uid = d.get('request') and d['request'].uid or None
|
2013-10-04 11:41:55 +00:00
|
|
|
|
2014-04-09 12:46:26 +00:00
|
|
|
template = self.eval_format(template_attributes["call"], d)
|
|
|
|
try:
|
|
|
|
template = int(template)
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
return self.render(cr, uid, template, d)
|
2013-06-27 15:08:07 +00:00
|
|
|
|
2014-04-08 07:52:05 +00:00
|
|
|
def render_tag_call_assets(self, element, template_attributes, generated_attributes, qwebcontext):
|
2014-04-09 16:17:58 +00:00
|
|
|
""" This special 't-call' tag can be used in order to aggregate/minify javascript and css assets"""
|
2014-07-02 14:01:36 +00:00
|
|
|
if len(element):
|
2014-06-24 16:52:38 +00:00
|
|
|
# An asset bundle is rendered in two differents contexts (when genereting html and
|
|
|
|
# when generating the bundle itself) so they must be qwebcontext free
|
|
|
|
# even '0' variable is forbidden
|
|
|
|
template = qwebcontext.get('__template__')
|
|
|
|
raise QWebException("t-call-assets cannot contain children nodes", template=template)
|
|
|
|
xmlid = template_attributes['call-assets']
|
|
|
|
cr, uid, context = [getattr(qwebcontext, attr) for attr in ('cr', 'uid', 'context')]
|
|
|
|
bundle = AssetsBundle(xmlid, cr=cr, uid=uid, context=context, registry=self.pool)
|
2014-05-08 11:51:57 +00:00
|
|
|
css = self.get_attr_bool(template_attributes.get('css'), default=True)
|
|
|
|
js = self.get_attr_bool(template_attributes.get('js'), default=True)
|
|
|
|
return bundle.to_html(css=css, js=js, debug=bool(qwebcontext.get('debug')))
|
2014-04-08 07:52:05 +00:00
|
|
|
|
2014-01-23 12:46:51 +00:00
|
|
|
def render_tag_set(self, element, template_attributes, generated_attributes, qwebcontext):
|
|
|
|
if "value" in template_attributes:
|
|
|
|
qwebcontext[template_attributes["set"]] = self.eval_object(template_attributes["value"], qwebcontext)
|
|
|
|
elif "valuef" in template_attributes:
|
|
|
|
qwebcontext[template_attributes["set"]] = self.eval_format(template_attributes["valuef"], qwebcontext)
|
2013-06-27 09:13:29 +00:00
|
|
|
else:
|
2014-01-23 12:46:51 +00:00
|
|
|
qwebcontext[template_attributes["set"]] = self.render_element(element, template_attributes, generated_attributes, qwebcontext)
|
2013-06-27 09:13:29 +00:00
|
|
|
return ""
|
2013-06-30 21:35:15 +00:00
|
|
|
|
2014-01-23 12:46:51 +00:00
|
|
|
def render_tag_field(self, element, template_attributes, generated_attributes, qwebcontext):
|
2013-07-01 15:55:41 +00:00
|
|
|
""" eg: <span t-record="browse_record(res.partner, 1)" t-field="phone">+1 555 555 8069</span>"""
|
2014-07-02 14:01:36 +00:00
|
|
|
node_name = element.tag
|
2013-09-27 12:45:23 +00:00
|
|
|
assert node_name not in ("table", "tbody", "thead", "tfoot", "tr", "td",
|
2013-11-28 15:36:30 +00:00
|
|
|
"li", "ul", "ol", "dl", "dt", "dd"),\
|
2013-09-17 11:30:22 +00:00
|
|
|
"RTE widgets do not work correctly on %r elements" % node_name
|
2013-09-25 12:10:28 +00:00
|
|
|
assert node_name != 't',\
|
|
|
|
"t-field can not be used on a t element, provide an actual HTML node"
|
2013-08-04 20:23:31 +00:00
|
|
|
|
2014-01-23 12:46:51 +00:00
|
|
|
record, field_name = template_attributes["field"].rsplit('.', 1)
|
|
|
|
record = self.eval_object(record, qwebcontext)
|
2013-07-01 15:55:41 +00:00
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
field = record._fields[field_name]
|
2014-01-23 12:46:51 +00:00
|
|
|
options = json.loads(template_attributes.get('field-options') or '{}')
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
field_type = get_field_type(field, options)
|
2013-09-26 14:51:26 +00:00
|
|
|
|
2013-10-07 12:51:55 +00:00
|
|
|
converter = self.get_converter_for(field_type)
|
2013-09-26 14:51:26 +00:00
|
|
|
|
2014-01-23 12:46:51 +00:00
|
|
|
return converter.to_html(qwebcontext.cr, qwebcontext.uid, field_name, record, options,
|
|
|
|
element, template_attributes, generated_attributes, qwebcontext, context=qwebcontext.context)
|
2013-10-07 09:15:56 +00:00
|
|
|
|
2013-10-07 12:51:55 +00:00
|
|
|
def get_converter_for(self, field_type):
|
2014-09-11 13:52:38 +00:00
|
|
|
""" returns a :class:`~openerp.models.Model` used to render a
|
|
|
|
``t-field``.
|
|
|
|
|
|
|
|
By default, tries to get the model named
|
|
|
|
:samp:`ir.qweb.field.{field_type}`, falling back on ``ir.qweb.field``.
|
|
|
|
|
|
|
|
:param str field_type: type or widget of field to render
|
|
|
|
"""
|
2014-04-09 12:46:26 +00:00
|
|
|
return self.pool.get('ir.qweb.field.' + field_type, self.pool['ir.qweb.field'])
|
2013-10-07 12:51:55 +00:00
|
|
|
|
2014-04-07 13:11:45 +00:00
|
|
|
def get_widget_for(self, widget):
|
2014-09-11 13:52:38 +00:00
|
|
|
""" returns a :class:`~openerp.models.Model` used to render a
|
|
|
|
``t-esc``
|
|
|
|
|
|
|
|
:param str widget: name of the widget to use, or ``None``
|
|
|
|
"""
|
2014-08-05 15:19:36 +00:00
|
|
|
widget_model = ('ir.qweb.widget.' + widget) if widget else 'ir.qweb.widget'
|
|
|
|
return self.pool.get(widget_model) or self.pool['ir.qweb.widget']
|
2014-04-07 13:11:45 +00:00
|
|
|
|
2014-05-08 11:51:57 +00:00
|
|
|
def get_attr_bool(self, attr, default=False):
|
|
|
|
if attr:
|
|
|
|
attr = attr.lower()
|
|
|
|
if attr in ('false', '0'):
|
|
|
|
return False
|
|
|
|
elif attr in ('true', '1'):
|
|
|
|
return True
|
|
|
|
return default
|
|
|
|
|
2014-01-19 17:44:37 +00:00
|
|
|
#--------------------------------------------------------------------
|
|
|
|
# QWeb Fields converters
|
|
|
|
#--------------------------------------------------------------------
|
2013-10-07 09:15:56 +00:00
|
|
|
|
|
|
|
class FieldConverter(osv.AbstractModel):
|
2013-10-07 12:51:55 +00:00
|
|
|
""" Used to convert a t-field specification into an output HTML field.
|
|
|
|
|
|
|
|
:meth:`~.to_html` is the entry point of this conversion from QWeb, it:
|
|
|
|
|
|
|
|
* converts the record value to html using :meth:`~.record_to_html`
|
|
|
|
* generates the metadata attributes (``data-oe-``) to set on the root
|
|
|
|
result node
|
|
|
|
* generates the root result node itself through :meth:`~.render_element`
|
|
|
|
"""
|
2013-10-07 09:15:56 +00:00
|
|
|
_name = 'ir.qweb.field'
|
|
|
|
|
|
|
|
def attributes(self, cr, uid, field_name, record, options,
|
2013-10-21 08:31:20 +00:00
|
|
|
source_element, g_att, t_att, qweb_context,
|
|
|
|
context=None):
|
2014-09-11 13:52:38 +00:00
|
|
|
""" attributes(cr, uid, field_name, record, options, source_element, g_att, t_att, qweb_context, context=None)
|
|
|
|
|
2013-10-07 12:51:55 +00:00
|
|
|
Generates the metadata attributes (prefixed by ``data-oe-`` for the
|
|
|
|
root node of the field conversion. Attribute values are escaped by the
|
2014-06-10 16:46:40 +00:00
|
|
|
parent.
|
2013-10-07 12:51:55 +00:00
|
|
|
|
|
|
|
The default attributes are:
|
|
|
|
|
|
|
|
* ``model``, the name of the record's model
|
|
|
|
* ``id`` the id of the record to which the field belongs
|
|
|
|
* ``field`` the name of the converted field
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
* ``type`` the logical field type (widget, may not match the field's
|
|
|
|
``type``, may not be any Field subclass name)
|
2013-10-07 12:51:55 +00:00
|
|
|
* ``translate``, a boolean flag (``0`` or ``1``) denoting whether the
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
field is translatable
|
2013-10-07 12:51:55 +00:00
|
|
|
* ``expression``, the original expression
|
|
|
|
|
|
|
|
:returns: iterable of (attribute name, attribute value) pairs.
|
|
|
|
"""
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
field = record._fields[field_name]
|
|
|
|
field_type = get_field_type(field, options)
|
2013-10-07 09:15:56 +00:00
|
|
|
return [
|
2014-07-06 14:44:26 +00:00
|
|
|
('data-oe-model', record._name),
|
2013-10-07 09:15:56 +00:00
|
|
|
('data-oe-id', record.id),
|
|
|
|
('data-oe-field', field_name),
|
|
|
|
('data-oe-type', field_type),
|
|
|
|
('data-oe-expression', t_att['field']),
|
|
|
|
]
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def value_to_html(self, cr, uid, value, field, options=None, context=None):
|
|
|
|
""" value_to_html(cr, uid, value, field, options=None, context=None)
|
2014-09-11 13:52:38 +00:00
|
|
|
|
|
|
|
Converts a single value to its HTML version/output
|
2013-10-07 09:15:56 +00:00
|
|
|
"""
|
2013-10-30 15:41:05 +00:00
|
|
|
if not value: return ''
|
2013-12-16 09:23:30 +00:00
|
|
|
return value
|
2013-10-07 09:15:56 +00:00
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def record_to_html(self, cr, uid, field_name, record, options=None, context=None):
|
|
|
|
""" record_to_html(cr, uid, field_name, record, options=None, context=None)
|
2014-09-11 13:52:38 +00:00
|
|
|
|
|
|
|
Converts the specified field of the browse_record ``record`` to HTML
|
2013-10-07 09:15:56 +00:00
|
|
|
"""
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
field = record._fields[field_name]
|
2013-10-07 09:15:56 +00:00
|
|
|
return self.value_to_html(
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
cr, uid, record[field_name], field, options=options, context=context)
|
2013-10-07 09:15:56 +00:00
|
|
|
|
|
|
|
def to_html(self, cr, uid, field_name, record, options,
|
2013-10-18 14:45:46 +00:00
|
|
|
source_element, t_att, g_att, qweb_context, context=None):
|
2014-09-11 13:52:38 +00:00
|
|
|
""" to_html(cr, uid, field_name, record, options, source_element, t_att, g_att, qweb_context, context=None)
|
|
|
|
|
|
|
|
Converts a ``t-field`` to its HTML output. A ``t-field`` may be
|
2013-10-07 12:51:55 +00:00
|
|
|
extended by a ``t-field-options``, which is a JSON-serialized mapping
|
|
|
|
of configuration values.
|
|
|
|
|
|
|
|
A default configuration key is ``widget`` which can override the
|
|
|
|
field's own ``_type``.
|
2013-10-07 09:15:56 +00:00
|
|
|
"""
|
2013-07-02 16:48:05 +00:00
|
|
|
try:
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
content = self.record_to_html(cr, uid, field_name, record, options, context=context)
|
2013-12-16 09:23:30 +00:00
|
|
|
if options.get('html-escape', True):
|
2014-06-10 16:46:40 +00:00
|
|
|
content = escape(content)
|
2013-12-16 09:23:30 +00:00
|
|
|
elif hasattr(content, '__html__'):
|
|
|
|
content = content.__html__()
|
2013-10-11 11:16:20 +00:00
|
|
|
except Exception:
|
|
|
|
_logger.warning("Could not get field %s for model %s",
|
2014-07-06 14:44:26 +00:00
|
|
|
field_name, record._name, exc_info=True)
|
2014-01-24 13:21:37 +00:00
|
|
|
content = None
|
2013-07-01 15:55:41 +00:00
|
|
|
|
2014-09-25 13:32:25 +00:00
|
|
|
inherit_branding = context and context.get('inherit_branding')
|
|
|
|
if not inherit_branding and context and context.get('inherit_branding_auto'):
|
|
|
|
inherit_branding = self.pool['ir.model.access'].check(cr, uid, record._name, 'write', False, context=context)
|
|
|
|
|
|
|
|
if inherit_branding:
|
2014-03-17 11:09:04 +00:00
|
|
|
# add branding attributes
|
|
|
|
g_att += ''.join(
|
2015-02-27 13:45:48 +00:00
|
|
|
_build_attribute(name, value)
|
2014-03-17 11:09:04 +00:00
|
|
|
for name, value in self.attributes(
|
|
|
|
cr, uid, field_name, record, options,
|
2015-07-13 10:04:46 +00:00
|
|
|
source_element, g_att, t_att, qweb_context, context=context)
|
2014-03-17 11:09:04 +00:00
|
|
|
)
|
2013-09-26 14:51:26 +00:00
|
|
|
|
2013-10-07 09:15:56 +00:00
|
|
|
return self.render_element(cr, uid, source_element, t_att, g_att,
|
|
|
|
qweb_context, content)
|
|
|
|
|
2013-10-11 11:16:20 +00:00
|
|
|
def qweb_object(self):
|
|
|
|
return self.pool['ir.qweb']
|
|
|
|
|
2013-10-07 12:51:55 +00:00
|
|
|
def render_element(self, cr, uid, source_element, t_att, g_att,
|
|
|
|
qweb_context, content):
|
2014-09-11 13:52:38 +00:00
|
|
|
""" render_element(cr, uid, source_element, t_att, g_att, qweb_context, content)
|
|
|
|
|
|
|
|
Final rendering hook, by default just calls ir.qweb's ``render_element``
|
2013-10-07 12:51:55 +00:00
|
|
|
"""
|
2013-10-11 11:16:20 +00:00
|
|
|
return self.qweb_object().render_element(
|
2013-10-07 09:15:56 +00:00
|
|
|
source_element, t_att, g_att, qweb_context, content or '')
|
|
|
|
|
2013-10-21 12:57:23 +00:00
|
|
|
def user_lang(self, cr, uid, context):
|
2014-09-11 13:52:38 +00:00
|
|
|
""" user_lang(cr, uid, context)
|
|
|
|
|
2013-10-21 12:57:23 +00:00
|
|
|
Fetches the res.lang object corresponding to the language code stored
|
|
|
|
in the user's context. Fallbacks to en_US if no lang is present in the
|
|
|
|
context *or the language code is not valid*.
|
|
|
|
|
|
|
|
:returns: res.lang browse_record
|
|
|
|
"""
|
|
|
|
if context is None: context = {}
|
|
|
|
|
|
|
|
lang_code = context.get('lang') or 'en_US'
|
|
|
|
Lang = self.pool['res.lang']
|
|
|
|
|
|
|
|
lang_ids = Lang.search(cr, uid, [('code', '=', lang_code)], context=context) \
|
|
|
|
or Lang.search(cr, uid, [('code', '=', 'en_US')], context=context)
|
|
|
|
|
|
|
|
return Lang.browse(cr, uid, lang_ids[0], context=context)
|
|
|
|
|
2013-10-07 09:15:56 +00:00
|
|
|
class FloatConverter(osv.AbstractModel):
|
|
|
|
_name = 'ir.qweb.field.float'
|
|
|
|
_inherit = 'ir.qweb.field'
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def precision(self, cr, uid, field, options=None, context=None):
|
|
|
|
_, precision = field.digits or (None, None)
|
2013-10-21 09:16:07 +00:00
|
|
|
return precision
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def value_to_html(self, cr, uid, value, field, options=None, context=None):
|
2013-12-06 10:25:55 +00:00
|
|
|
if context is None:
|
|
|
|
context = {}
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
precision = self.precision(cr, uid, field, options=options, context=context)
|
2013-10-22 08:54:36 +00:00
|
|
|
fmt = '%f' if precision is None else '%.{precision}f'
|
2013-10-21 12:57:23 +00:00
|
|
|
|
2013-12-03 21:19:03 +00:00
|
|
|
lang_code = context.get('lang') or 'en_US'
|
|
|
|
lang = self.pool['res.lang']
|
|
|
|
formatted = lang.format(cr, uid, [lang_code], fmt.format(precision=precision), value, grouping=True)
|
2013-10-07 09:15:56 +00:00
|
|
|
|
2013-10-22 08:54:36 +00:00
|
|
|
# %f does not strip trailing zeroes. %g does but its precision causes
|
|
|
|
# it to switch to scientific notation starting at a million *and* to
|
|
|
|
# strip decimals. So use %f and if no precision was specified manually
|
|
|
|
# strip trailing 0.
|
2014-05-26 09:06:49 +00:00
|
|
|
if precision is None:
|
2013-10-22 08:54:36 +00:00
|
|
|
formatted = re.sub(r'(?:(0|\d+?)0+)$', r'\1', formatted)
|
2013-12-16 09:23:30 +00:00
|
|
|
return formatted
|
2013-10-07 09:15:56 +00:00
|
|
|
|
2013-10-21 15:26:39 +00:00
|
|
|
class DateConverter(osv.AbstractModel):
|
|
|
|
_name = 'ir.qweb.field.date'
|
|
|
|
_inherit = 'ir.qweb.field'
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def value_to_html(self, cr, uid, value, field, options=None, context=None):
|
2014-10-10 14:20:10 +00:00
|
|
|
if not value or len(value)<10: return ''
|
2013-10-21 15:26:39 +00:00
|
|
|
lang = self.user_lang(cr, uid, context=context)
|
2013-12-02 07:33:13 +00:00
|
|
|
locale = babel.Locale.parse(lang.code)
|
2013-10-21 15:26:39 +00:00
|
|
|
|
|
|
|
if isinstance(value, basestring):
|
2013-11-29 10:39:43 +00:00
|
|
|
value = datetime.datetime.strptime(
|
2014-10-10 14:20:10 +00:00
|
|
|
value[:10], openerp.tools.DEFAULT_SERVER_DATE_FORMAT)
|
2013-10-21 15:26:39 +00:00
|
|
|
|
2013-12-02 07:33:13 +00:00
|
|
|
if options and 'format' in options:
|
|
|
|
pattern = options['format']
|
|
|
|
else:
|
|
|
|
strftime_pattern = lang.date_format
|
|
|
|
pattern = openerp.tools.posix_to_ldml(strftime_pattern, locale=locale)
|
|
|
|
|
2014-01-30 14:06:46 +00:00
|
|
|
return babel.dates.format_date(
|
2013-12-02 07:33:13 +00:00
|
|
|
value, format=pattern,
|
|
|
|
locale=locale)
|
2013-10-21 15:26:39 +00:00
|
|
|
|
|
|
|
class DateTimeConverter(osv.AbstractModel):
|
|
|
|
_name = 'ir.qweb.field.datetime'
|
|
|
|
_inherit = 'ir.qweb.field'
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def value_to_html(self, cr, uid, value, field, options=None, context=None):
|
2013-10-30 15:41:05 +00:00
|
|
|
if not value: return ''
|
2013-10-21 15:26:39 +00:00
|
|
|
lang = self.user_lang(cr, uid, context=context)
|
2013-12-02 07:33:13 +00:00
|
|
|
locale = babel.Locale.parse(lang.code)
|
2013-10-21 15:26:39 +00:00
|
|
|
|
|
|
|
if isinstance(value, basestring):
|
2013-11-29 10:39:43 +00:00
|
|
|
value = datetime.datetime.strptime(
|
|
|
|
value, openerp.tools.DEFAULT_SERVER_DATETIME_FORMAT)
|
2014-04-03 16:20:05 +00:00
|
|
|
value = fields.datetime.context_timestamp(
|
2013-10-21 15:26:39 +00:00
|
|
|
cr, uid, timestamp=value, context=context)
|
|
|
|
|
2013-12-02 07:33:13 +00:00
|
|
|
if options and 'format' in options:
|
|
|
|
pattern = options['format']
|
|
|
|
else:
|
2014-10-10 14:20:10 +00:00
|
|
|
strftime_pattern = (u"%s %s" % (lang.date_format, lang.time_format))
|
2013-12-02 07:33:13 +00:00
|
|
|
pattern = openerp.tools.posix_to_ldml(strftime_pattern, locale=locale)
|
|
|
|
|
2014-02-27 16:46:11 +00:00
|
|
|
if options and options.get('hide_seconds'):
|
|
|
|
pattern = pattern.replace(":ss", "").replace(":s", "")
|
2014-07-10 11:26:38 +00:00
|
|
|
|
2013-12-02 07:33:13 +00:00
|
|
|
return babel.dates.format_datetime(value, format=pattern, locale=locale)
|
2013-10-21 15:26:39 +00:00
|
|
|
|
2013-10-07 09:15:56 +00:00
|
|
|
class TextConverter(osv.AbstractModel):
|
|
|
|
_name = 'ir.qweb.field.text'
|
|
|
|
_inherit = 'ir.qweb.field'
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def value_to_html(self, cr, uid, value, field, options=None, context=None):
|
2013-10-07 09:15:56 +00:00
|
|
|
"""
|
|
|
|
Escapes the value and converts newlines to br. This is bullshit.
|
|
|
|
"""
|
2013-10-30 15:41:05 +00:00
|
|
|
if not value: return ''
|
2013-12-16 09:23:30 +00:00
|
|
|
|
|
|
|
return nl2br(value, options=options)
|
2013-10-07 09:15:56 +00:00
|
|
|
|
|
|
|
class SelectionConverter(osv.AbstractModel):
|
|
|
|
_name = 'ir.qweb.field.selection'
|
|
|
|
_inherit = 'ir.qweb.field'
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def record_to_html(self, cr, uid, field_name, record, options=None, context=None):
|
2013-10-07 09:15:56 +00:00
|
|
|
value = record[field_name]
|
2013-10-30 22:07:38 +00:00
|
|
|
if not value: return ''
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
field = record._fields[field_name]
|
|
|
|
selection = dict(field.get_description(record.env)['selection'])
|
2013-10-07 09:15:56 +00:00
|
|
|
return self.value_to_html(
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
cr, uid, selection[value], field, options=options)
|
2013-10-07 09:15:56 +00:00
|
|
|
|
|
|
|
class ManyToOneConverter(osv.AbstractModel):
|
|
|
|
_name = 'ir.qweb.field.many2one'
|
|
|
|
_inherit = 'ir.qweb.field'
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def record_to_html(self, cr, uid, field_name, record, options=None, context=None):
|
2013-12-02 09:56:38 +00:00
|
|
|
[read] = record.read([field_name])
|
2014-01-31 00:27:01 +00:00
|
|
|
if not read[field_name]: return ''
|
2013-12-02 09:56:38 +00:00
|
|
|
_, value = read[field_name]
|
2013-12-16 09:23:30 +00:00
|
|
|
return nl2br(value, options=options)
|
2013-10-07 09:15:56 +00:00
|
|
|
|
|
|
|
class HTMLConverter(osv.AbstractModel):
|
|
|
|
_name = 'ir.qweb.field.html'
|
|
|
|
_inherit = 'ir.qweb.field'
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def value_to_html(self, cr, uid, value, field, options=None, context=None):
|
2013-12-16 09:23:30 +00:00
|
|
|
return HTMLSafe(value or '')
|
2013-10-07 09:15:56 +00:00
|
|
|
|
2013-10-07 11:31:33 +00:00
|
|
|
class ImageConverter(osv.AbstractModel):
|
2013-10-07 12:51:55 +00:00
|
|
|
""" ``image`` widget rendering, inserts a data:uri-using image tag in the
|
|
|
|
document. May be overridden by e.g. the website module to generate links
|
|
|
|
instead.
|
|
|
|
|
|
|
|
.. todo:: what happens if different output need different converters? e.g.
|
|
|
|
reports may need embedded images or FS links whereas website
|
|
|
|
needs website-aware
|
|
|
|
"""
|
2013-10-07 11:31:33 +00:00
|
|
|
_name = 'ir.qweb.field.image'
|
2013-10-07 09:15:56 +00:00
|
|
|
_inherit = 'ir.qweb.field'
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def value_to_html(self, cr, uid, value, field, options=None, context=None):
|
2013-10-07 09:15:56 +00:00
|
|
|
try:
|
|
|
|
image = Image.open(cStringIO.StringIO(value.decode('base64')))
|
2013-10-07 11:31:33 +00:00
|
|
|
image.verify()
|
2013-10-07 09:15:56 +00:00
|
|
|
except IOError:
|
|
|
|
raise ValueError("Non-image binary fields can not be converted to HTML")
|
2013-10-07 12:51:55 +00:00
|
|
|
except: # image.verify() throws "suitable exceptions", I have no idea what they are
|
2013-10-07 09:15:56 +00:00
|
|
|
raise ValueError("Invalid image content")
|
|
|
|
|
2013-12-16 09:23:30 +00:00
|
|
|
return HTMLSafe('<img src="data:%s;base64,%s">' % (Image.MIME[image.format], value))
|
2013-10-07 09:15:56 +00:00
|
|
|
|
2013-10-08 12:20:06 +00:00
|
|
|
class MonetaryConverter(osv.AbstractModel):
|
2013-10-11 14:25:12 +00:00
|
|
|
""" ``monetary`` converter, has a mandatory option
|
|
|
|
``display_currency``.
|
2013-10-07 14:53:46 +00:00
|
|
|
|
2013-10-21 10:05:43 +00:00
|
|
|
The currency is used for formatting *and rounding* of the float value. It
|
|
|
|
is assumed that the linked res_currency has a non-empty rounding value and
|
|
|
|
res.currency's ``round`` method is used to perform rounding.
|
|
|
|
|
2013-10-11 11:16:20 +00:00
|
|
|
.. note:: the monetary converter internally adds the qweb context to its
|
|
|
|
options mapping, so that the context is available to callees.
|
|
|
|
It's set under the ``_qweb_context`` key.
|
2013-10-07 14:53:46 +00:00
|
|
|
"""
|
2013-10-08 12:20:06 +00:00
|
|
|
_name = 'ir.qweb.field.monetary'
|
2013-10-07 14:53:46 +00:00
|
|
|
_inherit = 'ir.qweb.field'
|
|
|
|
|
2013-10-11 11:16:20 +00:00
|
|
|
def to_html(self, cr, uid, field_name, record, options,
|
2013-10-21 08:31:20 +00:00
|
|
|
source_element, t_att, g_att, qweb_context, context=None):
|
2013-10-11 11:16:20 +00:00
|
|
|
options['_qweb_context'] = qweb_context
|
|
|
|
return super(MonetaryConverter, self).to_html(
|
|
|
|
cr, uid, field_name, record, options,
|
2013-10-21 08:31:20 +00:00
|
|
|
source_element, t_att, g_att, qweb_context, context=context)
|
2013-10-11 11:16:20 +00:00
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def record_to_html(self, cr, uid, field_name, record, options, context=None):
|
2013-12-06 10:27:14 +00:00
|
|
|
if context is None:
|
|
|
|
context = {}
|
2013-10-14 09:36:57 +00:00
|
|
|
Currency = self.pool['res.currency']
|
2014-06-18 15:43:14 +00:00
|
|
|
display_currency = self.display_currency(cr, uid, options['display_currency'], options)
|
2013-10-11 11:16:20 +00:00
|
|
|
|
2013-10-21 12:57:23 +00:00
|
|
|
# lang.format mandates a sprintf-style format. These formats are non-
|
|
|
|
# minimal (they have a default fixed precision instead), and
|
|
|
|
# lang.format will not set one by default. currency.round will not
|
|
|
|
# provide one either. So we need to generate a precision value
|
|
|
|
# (integer > 0) from the currency's rounding (a float generally < 1.0).
|
|
|
|
#
|
|
|
|
# The log10 of the rounding should be the number of digits involved if
|
|
|
|
# negative, if positive clamp to 0 digits and call it a day.
|
|
|
|
# nb: int() ~ floor(), we want nearest rounding instead
|
2014-11-13 14:33:26 +00:00
|
|
|
precision = int(math.floor(math.log10(display_currency.rounding)))
|
2013-10-21 12:57:23 +00:00
|
|
|
fmt = "%.{0}f".format(-precision if precision < 0 else 0)
|
|
|
|
|
2014-06-18 15:43:14 +00:00
|
|
|
from_amount = record[field_name]
|
|
|
|
|
|
|
|
if options.get('from_currency'):
|
|
|
|
from_currency = self.display_currency(cr, uid, options['from_currency'], options)
|
|
|
|
from_amount = Currency.compute(cr, uid, from_currency.id, display_currency.id, from_amount)
|
|
|
|
|
2013-12-03 21:19:03 +00:00
|
|
|
lang_code = context.get('lang') or 'en_US'
|
|
|
|
lang = self.pool['res.lang']
|
2014-07-10 11:26:38 +00:00
|
|
|
formatted_amount = lang.format(cr, uid, [lang_code],
|
2014-06-18 15:43:14 +00:00
|
|
|
fmt, Currency.round(cr, uid, display_currency, from_amount),
|
2013-10-21 12:57:23 +00:00
|
|
|
grouping=True, monetary=True)
|
|
|
|
|
|
|
|
pre = post = u''
|
2014-06-18 15:43:14 +00:00
|
|
|
if display_currency.position == 'before':
|
2015-04-29 08:17:17 +00:00
|
|
|
pre = u'{symbol}\N{NO-BREAK SPACE}'
|
2013-10-07 15:03:30 +00:00
|
|
|
else:
|
2015-04-29 08:17:17 +00:00
|
|
|
post = u'\N{NO-BREAK SPACE}{symbol}'
|
2013-10-21 12:57:23 +00:00
|
|
|
|
2013-12-16 09:23:30 +00:00
|
|
|
return HTMLSafe(u'{pre}<span class="oe_currency_value">{0}</span>{post}'.format(
|
2013-10-21 12:57:23 +00:00
|
|
|
formatted_amount,
|
|
|
|
pre=pre, post=post,
|
|
|
|
).format(
|
2014-06-18 15:43:14 +00:00
|
|
|
symbol=display_currency.symbol,
|
2013-12-16 09:23:30 +00:00
|
|
|
))
|
2013-10-07 14:53:46 +00:00
|
|
|
|
2014-06-18 15:43:14 +00:00
|
|
|
def display_currency(self, cr, uid, currency, options):
|
2013-10-11 11:16:20 +00:00
|
|
|
return self.qweb_object().eval_object(
|
2014-06-18 15:43:14 +00:00
|
|
|
currency, options['_qweb_context'])
|
2013-10-11 11:16:20 +00:00
|
|
|
|
2013-11-28 15:36:30 +00:00
|
|
|
TIMEDELTA_UNITS = (
|
|
|
|
('year', 3600 * 24 * 365),
|
|
|
|
('month', 3600 * 24 * 30),
|
|
|
|
('week', 3600 * 24 * 7),
|
|
|
|
('day', 3600 * 24),
|
|
|
|
('hour', 3600),
|
|
|
|
('minute', 60),
|
|
|
|
('second', 1)
|
|
|
|
)
|
|
|
|
class DurationConverter(osv.AbstractModel):
|
|
|
|
""" ``duration`` converter, to display integral or fractional values as
|
|
|
|
human-readable time spans (e.g. 1.5 as "1 hour 30 minutes").
|
|
|
|
|
|
|
|
Can be used on any numerical field.
|
|
|
|
|
|
|
|
Has a mandatory option ``unit`` which can be one of ``second``, ``minute``,
|
|
|
|
``hour``, ``day``, ``week`` or ``year``, used to interpret the numerical
|
|
|
|
field value before converting it.
|
|
|
|
|
|
|
|
Sub-second values will be ignored.
|
|
|
|
"""
|
|
|
|
_name = 'ir.qweb.field.duration'
|
|
|
|
_inherit = 'ir.qweb.field'
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def value_to_html(self, cr, uid, value, field, options=None, context=None):
|
2013-11-28 15:36:30 +00:00
|
|
|
units = dict(TIMEDELTA_UNITS)
|
|
|
|
if value < 0:
|
|
|
|
raise ValueError(_("Durations can't be negative"))
|
|
|
|
if not options or options.get('unit') not in units:
|
|
|
|
raise ValueError(_("A unit must be provided to duration widgets"))
|
|
|
|
|
|
|
|
locale = babel.Locale.parse(
|
|
|
|
self.user_lang(cr, uid, context=context).code)
|
|
|
|
factor = units[options['unit']]
|
|
|
|
|
|
|
|
sections = []
|
|
|
|
r = value * factor
|
|
|
|
for unit, secs_per_unit in TIMEDELTA_UNITS:
|
|
|
|
v, r = divmod(r, secs_per_unit)
|
|
|
|
if not v: continue
|
|
|
|
section = babel.dates.format_timedelta(
|
|
|
|
v*secs_per_unit, threshold=1, locale=locale)
|
|
|
|
if section:
|
|
|
|
sections.append(section)
|
2014-05-19 15:37:00 +00:00
|
|
|
return ' '.join(sections)
|
|
|
|
|
2013-11-28 15:36:30 +00:00
|
|
|
|
2013-11-29 08:52:56 +00:00
|
|
|
class RelativeDatetimeConverter(osv.AbstractModel):
|
|
|
|
_name = 'ir.qweb.field.relative'
|
|
|
|
_inherit = 'ir.qweb.field'
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def value_to_html(self, cr, uid, value, field, options=None, context=None):
|
2013-11-29 08:52:56 +00:00
|
|
|
parse_format = openerp.tools.DEFAULT_SERVER_DATETIME_FORMAT
|
|
|
|
locale = babel.Locale.parse(
|
|
|
|
self.user_lang(cr, uid, context=context).code)
|
|
|
|
|
|
|
|
if isinstance(value, basestring):
|
|
|
|
value = datetime.datetime.strptime(value, parse_format)
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
# value should be a naive datetime in UTC. So is fields.Datetime.now()
|
|
|
|
reference = datetime.datetime.strptime(field.now(), parse_format)
|
2013-11-29 08:52:56 +00:00
|
|
|
|
|
|
|
return babel.dates.format_timedelta(
|
|
|
|
value - reference, add_direction=True, locale=locale)
|
|
|
|
|
2014-03-24 13:57:23 +00:00
|
|
|
class Contact(orm.AbstractModel):
|
|
|
|
_name = 'ir.qweb.field.contact'
|
|
|
|
_inherit = 'ir.qweb.field.many2one'
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def record_to_html(self, cr, uid, field_name, record, options=None, context=None):
|
2014-09-09 16:16:21 +00:00
|
|
|
if context is None:
|
|
|
|
context = {}
|
|
|
|
|
2014-04-11 09:16:21 +00:00
|
|
|
if options is None:
|
|
|
|
options = {}
|
2014-03-24 13:57:23 +00:00
|
|
|
opf = options.get('fields') or ["name", "address", "phone", "mobile", "fax", "email"]
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
value_rec = record[field_name]
|
|
|
|
if not value_rec:
|
|
|
|
return None
|
|
|
|
value_rec = value_rec.sudo().with_context(show_address=True)
|
2014-11-05 12:37:56 +00:00
|
|
|
value = value_rec.name_get()[0][1]
|
2014-03-24 13:57:23 +00:00
|
|
|
|
|
|
|
val = {
|
|
|
|
'name': value.split("\n")[0],
|
2014-06-10 16:46:40 +00:00
|
|
|
'address': escape("\n".join(value.split("\n")[1:])),
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
'phone': value_rec.phone,
|
|
|
|
'mobile': value_rec.mobile,
|
|
|
|
'fax': value_rec.fax,
|
|
|
|
'city': value_rec.city,
|
|
|
|
'country_id': value_rec.country_id.display_name,
|
|
|
|
'website': value_rec.website,
|
|
|
|
'email': value_rec.email,
|
2014-03-24 13:57:23 +00:00
|
|
|
'fields': opf,
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
'object': value_rec,
|
2014-03-24 13:57:23 +00:00
|
|
|
'options': options
|
|
|
|
}
|
|
|
|
|
|
|
|
html = self.pool["ir.ui.view"].render(cr, uid, "base.contact", val, engine='ir.qweb', context=context).decode('utf8')
|
|
|
|
|
|
|
|
return HTMLSafe(html)
|
|
|
|
|
2014-04-09 12:46:26 +00:00
|
|
|
class QwebView(orm.AbstractModel):
|
|
|
|
_name = 'ir.qweb.field.qweb'
|
|
|
|
_inherit = 'ir.qweb.field.many2one'
|
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def record_to_html(self, cr, uid, field_name, record, options=None, context=None):
|
2014-04-09 12:46:26 +00:00
|
|
|
if not getattr(record, field_name):
|
|
|
|
return None
|
|
|
|
|
|
|
|
view = getattr(record, field_name)
|
|
|
|
|
|
|
|
if view._model._name != "ir.ui.view":
|
|
|
|
_logger.warning("%s.%s must be a 'ir.ui.view' model." % (record, field_name))
|
|
|
|
return None
|
|
|
|
|
|
|
|
ctx = (context or {}).copy()
|
|
|
|
ctx['object'] = record
|
|
|
|
html = view.render(ctx, engine='ir.qweb', context=ctx).decode('utf8')
|
|
|
|
|
|
|
|
return HTMLSafe(html)
|
|
|
|
|
2014-04-07 13:11:45 +00:00
|
|
|
class QwebWidget(osv.AbstractModel):
|
|
|
|
_name = 'ir.qweb.widget'
|
|
|
|
|
|
|
|
def _format(self, inner, options, qwebcontext):
|
|
|
|
return self.pool['ir.qweb'].eval_str(inner, qwebcontext)
|
|
|
|
|
|
|
|
def format(self, inner, options, qwebcontext):
|
2014-06-10 16:46:40 +00:00
|
|
|
return escape(self._format(inner, options, qwebcontext))
|
2014-04-07 13:11:45 +00:00
|
|
|
|
|
|
|
class QwebWidgetMonetary(osv.AbstractModel):
|
|
|
|
_name = 'ir.qweb.widget.monetary'
|
|
|
|
_inherit = 'ir.qweb.widget'
|
|
|
|
|
|
|
|
def _format(self, inner, options, qwebcontext):
|
|
|
|
inner = self.pool['ir.qweb'].eval(inner, qwebcontext)
|
|
|
|
display = self.pool['ir.qweb'].eval_object(options['display_currency'], qwebcontext)
|
|
|
|
precision = int(round(math.log10(display.rounding)))
|
|
|
|
fmt = "%.{0}f".format(-precision if precision < 0 else 0)
|
|
|
|
lang_code = qwebcontext.context.get('lang') or 'en_US'
|
|
|
|
formatted_amount = self.pool['res.lang'].format(
|
|
|
|
qwebcontext.cr, qwebcontext.uid, [lang_code], fmt, inner, grouping=True, monetary=True
|
|
|
|
)
|
|
|
|
pre = post = u''
|
|
|
|
if display.position == 'before':
|
2015-04-29 08:17:17 +00:00
|
|
|
pre = u'{symbol}\N{NO-BREAK SPACE}'
|
2014-04-07 13:11:45 +00:00
|
|
|
else:
|
2015-04-29 08:17:17 +00:00
|
|
|
post = u'\N{NO-BREAK SPACE}{symbol}'
|
2014-04-07 13:11:45 +00:00
|
|
|
|
|
|
|
return u'{pre}{0}{post}'.format(
|
|
|
|
formatted_amount, pre=pre, post=post
|
|
|
|
).format(symbol=display.symbol,)
|
|
|
|
|
2013-12-16 09:23:30 +00:00
|
|
|
class HTMLSafe(object):
|
|
|
|
""" HTMLSafe string wrapper, Werkzeug's escape() has special handling for
|
|
|
|
objects with a ``__html__`` methods but AFAIK does not provide any such
|
|
|
|
object.
|
|
|
|
|
|
|
|
Wrapping a string in HTML will prevent its escaping
|
|
|
|
"""
|
|
|
|
__slots__ = ['string']
|
|
|
|
def __init__(self, string):
|
|
|
|
self.string = string
|
|
|
|
def __html__(self):
|
|
|
|
return self.string
|
|
|
|
def __str__(self):
|
|
|
|
s = self.string
|
|
|
|
if isinstance(s, unicode):
|
|
|
|
return s.encode('utf-8')
|
|
|
|
return s
|
|
|
|
def __unicode__(self):
|
|
|
|
s = self.string
|
|
|
|
if isinstance(s, str):
|
|
|
|
return s.decode('utf-8')
|
|
|
|
return s
|
|
|
|
|
|
|
|
def nl2br(string, options=None):
|
|
|
|
""" Converts newlines to HTML linebreaks in ``string``. Automatically
|
|
|
|
escapes content unless options['html-escape'] is set to False, and returns
|
|
|
|
the result wrapped in an HTMLSafe object.
|
|
|
|
|
|
|
|
:param str string:
|
|
|
|
:param dict options:
|
|
|
|
:rtype: HTMLSafe
|
|
|
|
"""
|
|
|
|
if options is None: options = {}
|
|
|
|
|
|
|
|
if options.get('html-escape', True):
|
2014-06-10 16:46:40 +00:00
|
|
|
string = escape(string)
|
2013-12-16 09:23:30 +00:00
|
|
|
return HTMLSafe(string.replace('\n', '<br>\n'))
|
2013-11-28 15:36:30 +00:00
|
|
|
|
[IMP] use model._fields instead of model._all_columns to cover all fields
The old-api model._all_columns contains information about model._columns and
inherited columns. This dictionary is missing new-api computed non-stored
fields, and the new field objects provide a more readable api...
This commit contains the following changes:
- adapt several methods of BaseModel to use fields instead of columns and
_all_columns
- copy all semantic-free attributes of related fields from their source
- add attribute 'group_operator' on integer and float fields
- base, base_action_rule, crm, edi, hr, mail, mass_mailing, pad,
payment_acquirer, share, website, website_crm, website_mail: simply use
_fields instead of _all_columns
- base, decimal_precision, website: adapt qweb rendering methods to use fields
instead of columns
2014-11-03 15:00:50 +00:00
|
|
|
def get_field_type(field, options):
|
|
|
|
""" Gets a t-field's effective type from the field definition and its options """
|
|
|
|
return options.get('widget', field.type)
|
2013-07-01 15:55:41 +00:00
|
|
|
|
2014-06-30 12:45:41 +00:00
|
|
|
class AssetError(Exception):
|
|
|
|
pass
|
|
|
|
class AssetNotFound(AssetError):
|
|
|
|
pass
|
2014-06-19 16:09:01 +00:00
|
|
|
|
2014-04-09 16:17:58 +00:00
|
|
|
class AssetsBundle(object):
|
2014-06-26 14:49:51 +00:00
|
|
|
# Sass installation:
|
|
|
|
#
|
|
|
|
# sudo gem install sass compass bootstrap-sass
|
|
|
|
#
|
|
|
|
# If the following error is encountered:
|
|
|
|
# 'ERROR: Cannot load compass.'
|
|
|
|
# Use this:
|
|
|
|
# sudo gem install compass --pre
|
|
|
|
cmd_sass = ['sass', '--stdin', '-t', 'compressed', '--unix-newlines', '--compass', '-r', 'bootstrap-sass']
|
2014-04-17 13:12:49 +00:00
|
|
|
rx_css_import = re.compile("(@import[^;{]+;?)", re.M)
|
2014-06-26 15:40:30 +00:00
|
|
|
rx_sass_import = re.compile("""(@import\s?['"]([^'"]+)['"])""")
|
2014-06-26 14:49:51 +00:00
|
|
|
rx_css_split = re.compile("\/\*\! ([a-f0-9-]+) \*\/")
|
2014-04-10 10:18:47 +00:00
|
|
|
|
2014-06-24 16:52:38 +00:00
|
|
|
def __init__(self, xmlid, debug=False, cr=None, uid=None, context=None, registry=None):
|
2014-04-09 16:17:58 +00:00
|
|
|
self.xmlid = xmlid
|
2014-06-24 16:52:38 +00:00
|
|
|
self.cr = request.cr if cr is None else cr
|
|
|
|
self.uid = request.uid if uid is None else uid
|
|
|
|
self.context = request.context if context is None else context
|
|
|
|
self.registry = request.registry if registry is None else registry
|
2014-04-09 16:17:58 +00:00
|
|
|
self.javascripts = []
|
|
|
|
self.stylesheets = []
|
2014-06-26 14:49:51 +00:00
|
|
|
self.css_errors = []
|
2014-04-09 16:17:58 +00:00
|
|
|
self.remains = []
|
2014-04-10 15:54:12 +00:00
|
|
|
self._checksum = None
|
2014-06-24 16:52:38 +00:00
|
|
|
|
|
|
|
context = self.context.copy()
|
2014-06-26 16:18:12 +00:00
|
|
|
context['inherit_branding'] = False
|
2014-09-16 14:27:27 +00:00
|
|
|
context['rendering_bundle'] = True
|
2014-06-26 16:18:12 +00:00
|
|
|
self.html = self.registry['ir.ui.view'].render(self.cr, self.uid, xmlid, context=context)
|
|
|
|
self.parse()
|
|
|
|
|
|
|
|
def parse(self):
|
2014-07-02 14:01:36 +00:00
|
|
|
fragments = html.fragments_fromstring(self.html)
|
2014-04-09 16:17:58 +00:00
|
|
|
for el in fragments:
|
2014-04-16 15:35:36 +00:00
|
|
|
if isinstance(el, basestring):
|
2014-04-09 16:17:58 +00:00
|
|
|
self.remains.append(el)
|
2014-07-02 14:01:36 +00:00
|
|
|
elif isinstance(el, html.HtmlElement):
|
2014-07-01 13:21:36 +00:00
|
|
|
src = el.get('src', '')
|
|
|
|
href = el.get('href', '')
|
2014-06-26 14:49:51 +00:00
|
|
|
atype = el.get('type')
|
2014-07-01 08:02:55 +00:00
|
|
|
media = el.get('media')
|
2014-04-09 16:17:58 +00:00
|
|
|
if el.tag == 'style':
|
2014-06-26 14:49:51 +00:00
|
|
|
if atype == 'text/sass' or src.endswith('.sass'):
|
2014-07-01 08:02:55 +00:00
|
|
|
self.stylesheets.append(SassAsset(self, inline=el.text, media=media))
|
2014-06-26 14:49:51 +00:00
|
|
|
else:
|
2014-07-01 08:02:55 +00:00
|
|
|
self.stylesheets.append(StylesheetAsset(self, inline=el.text, media=media))
|
2014-04-16 15:35:36 +00:00
|
|
|
elif el.tag == 'link' and el.get('rel') == 'stylesheet' and self.can_aggregate(href):
|
2014-06-26 14:49:51 +00:00
|
|
|
if href.endswith('.sass') or atype == 'text/sass':
|
2014-07-01 08:02:55 +00:00
|
|
|
self.stylesheets.append(SassAsset(self, url=href, media=media))
|
2014-06-26 14:49:51 +00:00
|
|
|
else:
|
2014-07-01 08:02:55 +00:00
|
|
|
self.stylesheets.append(StylesheetAsset(self, url=href, media=media))
|
2014-04-09 16:17:58 +00:00
|
|
|
elif el.tag == 'script' and not src:
|
2014-06-19 16:09:01 +00:00
|
|
|
self.javascripts.append(JavascriptAsset(self, inline=el.text))
|
2014-04-10 17:40:25 +00:00
|
|
|
elif el.tag == 'script' and self.can_aggregate(src):
|
2014-06-19 16:09:01 +00:00
|
|
|
self.javascripts.append(JavascriptAsset(self, url=src))
|
2014-04-09 16:17:58 +00:00
|
|
|
else:
|
2014-07-02 14:01:36 +00:00
|
|
|
self.remains.append(html.tostring(el))
|
2014-04-09 16:17:58 +00:00
|
|
|
else:
|
|
|
|
try:
|
2014-07-02 14:01:36 +00:00
|
|
|
self.remains.append(html.tostring(el))
|
2014-04-09 16:17:58 +00:00
|
|
|
except Exception:
|
2014-04-10 14:32:24 +00:00
|
|
|
# notYETimplementederror
|
2014-04-09 16:17:58 +00:00
|
|
|
raise NotImplementedError
|
|
|
|
|
2014-04-10 17:40:25 +00:00
|
|
|
def can_aggregate(self, url):
|
2014-04-16 15:35:36 +00:00
|
|
|
return not urlparse(url).netloc and not url.startswith(('/web/css', '/web/js'))
|
2014-04-09 16:17:58 +00:00
|
|
|
|
2014-06-19 16:09:01 +00:00
|
|
|
def to_html(self, sep=None, css=True, js=True, debug=False):
|
|
|
|
if sep is None:
|
|
|
|
sep = '\n '
|
2014-04-16 15:35:36 +00:00
|
|
|
response = []
|
2014-05-08 11:51:57 +00:00
|
|
|
if debug:
|
2014-06-30 17:17:47 +00:00
|
|
|
if css and self.stylesheets:
|
2014-06-30 12:45:41 +00:00
|
|
|
self.compile_sass()
|
2014-05-08 11:51:57 +00:00
|
|
|
for style in self.stylesheets:
|
|
|
|
response.append(style.to_html())
|
|
|
|
if js:
|
|
|
|
for jscript in self.javascripts:
|
|
|
|
response.append(jscript.to_html())
|
|
|
|
else:
|
2014-09-16 14:27:27 +00:00
|
|
|
url_for = self.context.get('url_for', lambda url: url)
|
2014-05-08 11:51:57 +00:00
|
|
|
if css and self.stylesheets:
|
2015-04-01 22:55:26 +00:00
|
|
|
suffix = ''
|
|
|
|
if request:
|
|
|
|
ua = request.httprequest.user_agent
|
|
|
|
if ua.browser == "msie" and int((ua.version or '0').split('.')[0]) < 10:
|
|
|
|
suffix = '.0'
|
|
|
|
href = '/web/css%s/%s/%s' % (suffix, self.xmlid, self.version)
|
2014-09-16 14:27:27 +00:00
|
|
|
response.append('<link href="%s" rel="stylesheet"/>' % url_for(href))
|
2014-06-30 12:45:41 +00:00
|
|
|
if js:
|
2014-09-16 14:27:27 +00:00
|
|
|
src = '/web/js/%s/%s' % (self.xmlid, self.version)
|
|
|
|
response.append('<script type="text/javascript" src="%s"></script>' % url_for(src))
|
2014-04-16 15:35:36 +00:00
|
|
|
response.extend(self.remains)
|
2014-05-08 11:51:57 +00:00
|
|
|
return sep + sep.join(response)
|
2014-04-09 16:17:58 +00:00
|
|
|
|
2014-06-19 16:09:01 +00:00
|
|
|
@lazy_property
|
2014-04-10 14:32:24 +00:00
|
|
|
def last_modified(self):
|
2014-06-26 16:18:12 +00:00
|
|
|
"""Returns last modified date of linked files"""
|
2014-04-16 15:35:36 +00:00
|
|
|
return max(itertools.chain(
|
|
|
|
(asset.last_modified for asset in self.javascripts),
|
|
|
|
(asset.last_modified for asset in self.stylesheets),
|
|
|
|
))
|
2014-04-10 14:32:24 +00:00
|
|
|
|
2014-06-24 16:52:38 +00:00
|
|
|
@lazy_property
|
|
|
|
def version(self):
|
2014-06-26 16:18:12 +00:00
|
|
|
return self.checksum[0:7]
|
2014-06-24 16:52:38 +00:00
|
|
|
|
2014-06-19 16:09:01 +00:00
|
|
|
@lazy_property
|
2014-04-10 15:54:12 +00:00
|
|
|
def checksum(self):
|
2014-06-26 16:18:12 +00:00
|
|
|
"""
|
|
|
|
Not really a full checksum.
|
|
|
|
We compute a SHA1 on the rendered bundle + max linked files last_modified date
|
|
|
|
"""
|
|
|
|
check = self.html + str(self.last_modified)
|
|
|
|
return hashlib.sha1(check).hexdigest()
|
2014-04-10 15:54:12 +00:00
|
|
|
|
2014-04-10 16:47:44 +00:00
|
|
|
def js(self):
|
2014-08-18 13:57:51 +00:00
|
|
|
content = self.get_cache('js')
|
|
|
|
if content is None:
|
|
|
|
content = ';\n'.join(asset.minify() for asset in self.javascripts)
|
|
|
|
self.set_cache('js', content)
|
|
|
|
return content
|
2014-04-09 16:17:58 +00:00
|
|
|
|
2015-04-01 22:55:26 +00:00
|
|
|
def css(self, page_number=None):
|
|
|
|
if page_number is not None:
|
|
|
|
return self.css_page(page_number)
|
|
|
|
|
2014-08-18 13:57:51 +00:00
|
|
|
content = self.get_cache('css')
|
|
|
|
if content is None:
|
2014-06-30 12:45:41 +00:00
|
|
|
self.compile_sass()
|
2014-04-16 15:35:36 +00:00
|
|
|
content = '\n'.join(asset.minify() for asset in self.stylesheets)
|
2014-06-26 14:49:51 +00:00
|
|
|
|
|
|
|
if self.css_errors:
|
|
|
|
msg = '\n'.join(self.css_errors)
|
|
|
|
content += self.css_message(msg.replace('\n', '\\A '))
|
|
|
|
|
2014-04-18 13:30:17 +00:00
|
|
|
# move up all @import rules to the top
|
2014-04-10 16:47:44 +00:00
|
|
|
matches = []
|
|
|
|
def push(matchobj):
|
|
|
|
matches.append(matchobj.group(0))
|
|
|
|
return ''
|
|
|
|
|
|
|
|
content = re.sub(self.rx_css_import, push, content)
|
|
|
|
|
|
|
|
matches.append(content)
|
2014-04-17 12:52:13 +00:00
|
|
|
content = u'\n'.join(matches)
|
2015-04-01 22:55:26 +00:00
|
|
|
if not self.css_errors:
|
|
|
|
self.set_cache('css', content)
|
|
|
|
content = content.encode('utf-8')
|
2014-08-18 13:57:51 +00:00
|
|
|
|
|
|
|
return content
|
|
|
|
|
2015-04-01 22:55:26 +00:00
|
|
|
def css_page(self, page_number):
|
|
|
|
content = self.get_cache('css.%d' % (page_number,))
|
|
|
|
if page_number:
|
|
|
|
return content
|
|
|
|
if content is None:
|
2015-04-07 09:15:40 +00:00
|
|
|
css = self.css().decode('utf-8')
|
2015-04-01 22:55:26 +00:00
|
|
|
re_rules = '([^{]+\{(?:[^{}]|\{[^{}]*\})*\})'
|
|
|
|
re_selectors = '()(?:\s*@media\s*[^{]*\{)?(?:\s*(?:[^,{]*(?:,|\{(?:[^}]*\}))))'
|
|
|
|
css_url = '@import url(\'/web/css.%%d/%s/%s\');' % (self.xmlid, self.version)
|
|
|
|
pages = [[]]
|
|
|
|
page = pages[0]
|
|
|
|
page_selectors = 0
|
|
|
|
for rule in re.findall(re_rules, css):
|
|
|
|
selectors = len(re.findall(re_selectors, rule))
|
|
|
|
if page_selectors + selectors < MAX_CSS_RULES:
|
|
|
|
page_selectors += selectors
|
|
|
|
page.append(rule)
|
|
|
|
else:
|
|
|
|
pages.append([rule])
|
|
|
|
page = pages[-1]
|
|
|
|
page_selectors = selectors
|
|
|
|
if len(pages) == 1:
|
|
|
|
pages = []
|
|
|
|
for idx, page in enumerate(pages):
|
2015-04-07 08:55:24 +00:00
|
|
|
self.set_cache("css.%d" % (idx+1), ''.join(page))
|
|
|
|
content = '\n'.join(css_url % i for i in range(1,len(pages)+1))
|
2015-04-01 22:55:26 +00:00
|
|
|
self.set_cache("css.0", content)
|
|
|
|
if not content:
|
|
|
|
return self.css()
|
|
|
|
return content
|
|
|
|
|
2014-08-18 13:57:51 +00:00
|
|
|
def get_cache(self, type):
|
|
|
|
content = None
|
|
|
|
domain = [('url', '=', '/web/%s/%s/%s' % (type, self.xmlid, self.version))]
|
2014-10-02 14:33:57 +00:00
|
|
|
bundle = self.registry['ir.attachment'].search_read(self.cr, openerp.SUPERUSER_ID, domain, ['datas'], context=self.context)
|
2014-09-03 16:44:22 +00:00
|
|
|
if bundle and bundle[0]['datas']:
|
2014-08-18 13:57:51 +00:00
|
|
|
content = bundle[0]['datas'].decode('base64')
|
|
|
|
return content
|
|
|
|
|
|
|
|
def set_cache(self, type, content):
|
|
|
|
ira = self.registry['ir.attachment']
|
|
|
|
url_prefix = '/web/%s/%s/' % (type, self.xmlid)
|
|
|
|
# Invalidate previous caches
|
2015-07-08 17:19:28 +00:00
|
|
|
try:
|
|
|
|
with self.cr.savepoint():
|
|
|
|
domain = [('url', '=like', url_prefix + '%')]
|
|
|
|
oids = ira.search(self.cr, openerp.SUPERUSER_ID, domain, context=self.context)
|
|
|
|
if oids:
|
|
|
|
ira.unlink(self.cr, openerp.SUPERUSER_ID, oids, context=self.context)
|
|
|
|
url = url_prefix + self.version
|
|
|
|
ira.create(self.cr, openerp.SUPERUSER_ID, dict(
|
2014-08-18 13:57:51 +00:00
|
|
|
datas=content.encode('utf8').encode('base64'),
|
|
|
|
type='binary',
|
|
|
|
name=url,
|
|
|
|
url=url,
|
|
|
|
), context=self.context)
|
2015-07-08 17:19:28 +00:00
|
|
|
except psycopg2.Error:
|
|
|
|
pass
|
2014-04-09 16:17:58 +00:00
|
|
|
|
2014-06-26 14:49:51 +00:00
|
|
|
def css_message(self, message):
|
|
|
|
return """
|
|
|
|
body:before {
|
|
|
|
background: #ffc;
|
|
|
|
width: 100%%;
|
|
|
|
font-size: 14px;
|
|
|
|
font-family: monospace;
|
|
|
|
white-space: pre;
|
|
|
|
content: "%s";
|
|
|
|
}
|
|
|
|
""" % message.replace('"', '\\"')
|
|
|
|
|
2014-06-30 12:45:41 +00:00
|
|
|
def compile_sass(self):
|
|
|
|
"""
|
|
|
|
Checks if the bundle contains any sass content, then compiles it to css.
|
|
|
|
Css compilation is done at the bundle level and not in the assets
|
|
|
|
because they are potentially interdependant.
|
|
|
|
"""
|
2014-06-26 14:49:51 +00:00
|
|
|
sass = [asset for asset in self.stylesheets if isinstance(asset, SassAsset)]
|
|
|
|
if not sass:
|
|
|
|
return
|
|
|
|
source = '\n'.join([asset.get_source() for asset in sass])
|
2014-06-26 15:40:30 +00:00
|
|
|
|
|
|
|
# move up all @import rules to the top and exclude file imports
|
|
|
|
imports = []
|
|
|
|
def push(matchobj):
|
|
|
|
ref = matchobj.group(2)
|
|
|
|
line = '@import "%s"' % ref
|
|
|
|
if '.' not in ref and line not in imports and not ref.startswith(('.', '/', '~')):
|
|
|
|
imports.append(line)
|
|
|
|
return ''
|
|
|
|
source = re.sub(self.rx_sass_import, push, source)
|
|
|
|
imports.append(source)
|
|
|
|
source = u'\n'.join(imports)
|
|
|
|
|
2014-06-26 14:49:51 +00:00
|
|
|
try:
|
|
|
|
compiler = Popen(self.cmd_sass, stdin=PIPE, stdout=PIPE, stderr=PIPE)
|
|
|
|
except Exception:
|
2014-06-30 12:45:41 +00:00
|
|
|
msg = "Could not find 'sass' program needed to compile sass/scss files"
|
2014-06-26 14:49:51 +00:00
|
|
|
_logger.error(msg)
|
|
|
|
self.css_errors.append(msg)
|
|
|
|
return
|
2014-06-30 12:45:41 +00:00
|
|
|
result = compiler.communicate(input=source.encode('utf-8'))
|
2014-06-26 14:49:51 +00:00
|
|
|
if compiler.returncode:
|
2014-07-01 16:38:01 +00:00
|
|
|
error = self.get_sass_error(''.join(result), source=source)
|
2014-06-30 12:45:41 +00:00
|
|
|
_logger.warning(error)
|
|
|
|
self.css_errors.append(error)
|
2014-06-26 14:49:51 +00:00
|
|
|
return
|
2014-06-30 12:45:41 +00:00
|
|
|
compiled = result[0].strip().decode('utf8')
|
|
|
|
fragments = self.rx_css_split.split(compiled)[1:]
|
2014-06-26 14:49:51 +00:00
|
|
|
while fragments:
|
|
|
|
asset_id = fragments.pop(0)
|
|
|
|
asset = next(asset for asset in sass if asset.id == asset_id)
|
2014-07-01 08:02:55 +00:00
|
|
|
asset._content = fragments.pop(0)
|
2014-06-26 14:49:51 +00:00
|
|
|
|
2014-06-30 12:45:41 +00:00
|
|
|
def get_sass_error(self, stderr, source=None):
|
|
|
|
# TODO: try to find out which asset the error belongs to
|
|
|
|
error = stderr.split('Load paths')[0].replace(' Use --trace for backtrace.', '')
|
|
|
|
error += "This error occured while compiling the bundle '%s' containing:" % self.xmlid
|
|
|
|
for asset in self.stylesheets:
|
|
|
|
if isinstance(asset, SassAsset):
|
|
|
|
error += '\n - %s' % (asset.url if asset.url else '<inline sass>')
|
|
|
|
return error
|
|
|
|
|
2014-04-09 16:17:58 +00:00
|
|
|
class WebAsset(object):
|
2014-06-26 14:49:51 +00:00
|
|
|
html_url = '%s'
|
|
|
|
|
2014-06-26 16:51:55 +00:00
|
|
|
def __init__(self, bundle, inline=None, url=None):
|
2014-06-26 14:49:51 +00:00
|
|
|
self.id = str(uuid.uuid4())
|
2014-06-19 16:09:01 +00:00
|
|
|
self.bundle = bundle
|
|
|
|
self.inline = inline
|
2014-04-09 16:17:58 +00:00
|
|
|
self.url = url
|
2014-06-26 16:51:55 +00:00
|
|
|
self.cr = bundle.cr
|
|
|
|
self.uid = bundle.uid
|
|
|
|
self.registry = bundle.registry
|
|
|
|
self.context = bundle.context
|
2014-07-01 08:02:55 +00:00
|
|
|
self._content = None
|
2014-06-19 16:09:01 +00:00
|
|
|
self._filename = None
|
|
|
|
self._ir_attach = None
|
2014-06-30 12:45:41 +00:00
|
|
|
name = '<inline asset>' if inline else url
|
|
|
|
self.name = "%s defined in bundle '%s'" % (name, bundle.xmlid)
|
2014-06-19 16:09:01 +00:00
|
|
|
if not inline and not url:
|
2014-06-24 16:52:38 +00:00
|
|
|
raise Exception("An asset should either be inlined or url linked")
|
2014-06-19 16:09:01 +00:00
|
|
|
|
|
|
|
def stat(self):
|
|
|
|
if not (self.inline or self._filename or self._ir_attach):
|
|
|
|
addon = filter(None, self.url.split('/'))[0]
|
2014-04-25 13:28:04 +00:00
|
|
|
try:
|
2014-05-05 16:09:53 +00:00
|
|
|
# Test url against modules static assets
|
2014-06-19 16:09:01 +00:00
|
|
|
mpath = openerp.http.addons_manifest[addon]['addons_path']
|
|
|
|
self._filename = mpath + self.url.replace('/', os.path.sep)
|
2014-04-25 13:28:04 +00:00
|
|
|
except Exception:
|
2014-05-05 16:09:53 +00:00
|
|
|
try:
|
|
|
|
# Test url against ir.attachments
|
2014-06-24 16:52:38 +00:00
|
|
|
fields = ['__last_update', 'datas', 'mimetype']
|
2014-05-05 16:09:53 +00:00
|
|
|
domain = [('type', '=', 'binary'), ('url', '=', self.url)]
|
2014-06-26 16:51:55 +00:00
|
|
|
ira = self.registry['ir.attachment']
|
2014-10-02 14:33:57 +00:00
|
|
|
attach = ira.search_read(self.cr, openerp.SUPERUSER_ID, domain, fields, context=self.context)
|
2014-06-19 16:09:01 +00:00
|
|
|
self._ir_attach = attach[0]
|
2014-05-05 16:09:53 +00:00
|
|
|
except Exception:
|
2014-06-30 12:45:41 +00:00
|
|
|
raise AssetNotFound("Could not find %s" % self.name)
|
2014-04-10 14:32:24 +00:00
|
|
|
|
2014-07-02 14:01:36 +00:00
|
|
|
def to_html(self):
|
2014-06-26 14:49:51 +00:00
|
|
|
raise NotImplementedError()
|
|
|
|
|
2014-06-19 16:09:01 +00:00
|
|
|
@lazy_property
|
|
|
|
def last_modified(self):
|
|
|
|
try:
|
|
|
|
self.stat()
|
|
|
|
if self._filename:
|
|
|
|
return datetime.datetime.fromtimestamp(os.path.getmtime(self._filename))
|
|
|
|
elif self._ir_attach:
|
|
|
|
server_format = openerp.tools.misc.DEFAULT_SERVER_DATETIME_FORMAT
|
|
|
|
last_update = self._ir_attach['__last_update']
|
|
|
|
try:
|
|
|
|
return datetime.datetime.strptime(last_update, server_format + '.%f')
|
|
|
|
except ValueError:
|
|
|
|
return datetime.datetime.strptime(last_update, server_format)
|
|
|
|
except Exception:
|
|
|
|
pass
|
|
|
|
return datetime.datetime(1970, 1, 1)
|
|
|
|
|
2014-07-01 08:02:55 +00:00
|
|
|
@property
|
2014-04-10 15:54:12 +00:00
|
|
|
def content(self):
|
2014-07-01 08:02:55 +00:00
|
|
|
if not self._content:
|
|
|
|
self._content = self.inline or self._fetch_content()
|
|
|
|
return self._content
|
2014-04-16 15:35:36 +00:00
|
|
|
|
2014-06-19 16:09:01 +00:00
|
|
|
def _fetch_content(self):
|
|
|
|
""" Fetch content from file or database"""
|
|
|
|
try:
|
2014-06-30 12:45:41 +00:00
|
|
|
self.stat()
|
2014-06-19 16:09:01 +00:00
|
|
|
if self._filename:
|
|
|
|
with open(self._filename, 'rb') as fp:
|
|
|
|
return fp.read().decode('utf-8')
|
|
|
|
else:
|
|
|
|
return self._ir_attach['datas'].decode('base64')
|
2014-06-30 12:45:41 +00:00
|
|
|
except UnicodeDecodeError:
|
|
|
|
raise AssetError('%s is not utf-8 encoded.' % self.name)
|
|
|
|
except IOError:
|
|
|
|
raise AssetNotFound('File %s does not exist.' % self.name)
|
|
|
|
except:
|
|
|
|
raise AssetError('Could not get content for %s.' % self.name)
|
2014-04-10 10:18:47 +00:00
|
|
|
|
|
|
|
def minify(self):
|
2014-04-10 15:54:12 +00:00
|
|
|
return self.content
|
|
|
|
|
2014-06-26 16:51:55 +00:00
|
|
|
def with_header(self, content=None):
|
|
|
|
if content is None:
|
|
|
|
content = self.content
|
2014-06-30 12:45:41 +00:00
|
|
|
return '\n/* %s */\n%s' % (self.name, content)
|
2014-06-26 14:49:51 +00:00
|
|
|
|
2014-04-09 16:17:58 +00:00
|
|
|
class JavascriptAsset(WebAsset):
|
2014-04-10 10:18:47 +00:00
|
|
|
def minify(self):
|
2014-06-26 14:49:51 +00:00
|
|
|
return self.with_header(rjsmin(self.content))
|
2014-04-09 16:17:58 +00:00
|
|
|
|
2014-06-19 16:09:01 +00:00
|
|
|
def _fetch_content(self):
|
|
|
|
try:
|
|
|
|
return super(JavascriptAsset, self)._fetch_content()
|
2014-06-30 12:45:41 +00:00
|
|
|
except AssetError, e:
|
|
|
|
return "console.error(%s);" % json.dumps(e.message)
|
2014-06-19 16:09:01 +00:00
|
|
|
|
2014-05-08 11:51:57 +00:00
|
|
|
def to_html(self):
|
|
|
|
if self.url:
|
2014-06-26 14:49:51 +00:00
|
|
|
return '<script type="text/javascript" src="%s"></script>' % (self.html_url % self.url)
|
2014-05-08 11:51:57 +00:00
|
|
|
else:
|
2014-06-26 16:51:55 +00:00
|
|
|
return '<script type="text/javascript" charset="utf-8">%s</script>' % self.with_header()
|
2014-05-08 11:51:57 +00:00
|
|
|
|
2014-04-09 16:17:58 +00:00
|
|
|
class StylesheetAsset(WebAsset):
|
2014-04-10 10:18:47 +00:00
|
|
|
rx_import = re.compile(r"""@import\s+('|")(?!'|"|/|https?://)""", re.U)
|
|
|
|
rx_url = re.compile(r"""url\s*\(\s*('|"|)(?!'|"|/|https?://|data:)""", re.U)
|
2014-04-17 14:20:12 +00:00
|
|
|
rx_sourceMap = re.compile(r'(/\*# sourceMappingURL=.*)', re.U)
|
2014-06-19 16:09:01 +00:00
|
|
|
rx_charset = re.compile(r'(@charset "[^"]+";)', re.U)
|
2014-04-10 10:18:47 +00:00
|
|
|
|
2014-07-01 08:02:55 +00:00
|
|
|
def __init__(self, *args, **kw):
|
|
|
|
self.media = kw.pop('media', None)
|
|
|
|
super(StylesheetAsset, self).__init__(*args, **kw)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def content(self):
|
|
|
|
content = super(StylesheetAsset, self).content
|
|
|
|
if self.media:
|
|
|
|
content = '@media %s { %s }' % (self.media, content)
|
|
|
|
return content
|
|
|
|
|
2014-06-19 16:09:01 +00:00
|
|
|
def _fetch_content(self):
|
|
|
|
try:
|
|
|
|
content = super(StylesheetAsset, self)._fetch_content()
|
2014-04-10 10:18:47 +00:00
|
|
|
web_dir = os.path.dirname(self.url)
|
|
|
|
|
2014-04-17 14:20:12 +00:00
|
|
|
content = self.rx_import.sub(
|
2014-04-10 10:18:47 +00:00
|
|
|
r"""@import \1%s/""" % (web_dir,),
|
|
|
|
content,
|
|
|
|
)
|
|
|
|
|
2014-04-17 14:20:12 +00:00
|
|
|
content = self.rx_url.sub(
|
2014-04-10 10:18:47 +00:00
|
|
|
r"url(\1%s/" % (web_dir,),
|
|
|
|
content,
|
|
|
|
)
|
2014-06-19 16:09:01 +00:00
|
|
|
|
|
|
|
# remove charset declarations, we only support utf-8
|
|
|
|
content = self.rx_charset.sub('', content)
|
2014-06-30 12:45:41 +00:00
|
|
|
except AssetError, e:
|
|
|
|
self.bundle.css_errors.append(e.message)
|
2014-06-26 14:49:51 +00:00
|
|
|
return ''
|
2014-04-10 10:18:47 +00:00
|
|
|
return content
|
|
|
|
|
2014-04-17 14:20:12 +00:00
|
|
|
def minify(self):
|
|
|
|
# remove existing sourcemaps, make no sense after re-mini
|
2014-05-01 19:05:44 +00:00
|
|
|
content = self.rx_sourceMap.sub('', self.content)
|
|
|
|
# comments
|
|
|
|
content = re.sub(r'/\*.*?\*/', '', content, flags=re.S)
|
|
|
|
# space
|
|
|
|
content = re.sub(r'\s+', ' ', content)
|
|
|
|
content = re.sub(r' *([{}]) *', r'\1', content)
|
2014-06-26 14:49:51 +00:00
|
|
|
return self.with_header(content)
|
2014-04-10 10:18:47 +00:00
|
|
|
|
2014-05-08 11:51:57 +00:00
|
|
|
def to_html(self):
|
2014-07-01 08:02:55 +00:00
|
|
|
media = (' media="%s"' % werkzeug.utils.escape(self.media)) if self.media else ''
|
2014-05-08 11:51:57 +00:00
|
|
|
if self.url:
|
2014-07-01 08:02:55 +00:00
|
|
|
href = self.html_url % self.url
|
|
|
|
return '<link rel="stylesheet" href="%s" type="text/css"%s/>' % (href, media)
|
2014-05-08 11:51:57 +00:00
|
|
|
else:
|
2014-07-01 08:02:55 +00:00
|
|
|
return '<style type="text/css"%s>%s</style>' % (media, self.with_header())
|
2014-06-26 14:49:51 +00:00
|
|
|
|
|
|
|
class SassAsset(StylesheetAsset):
|
|
|
|
html_url = '%s.css'
|
2014-06-30 16:41:29 +00:00
|
|
|
rx_indent = re.compile(r'^( +|\t+)', re.M)
|
|
|
|
indent = None
|
|
|
|
reindent = ' '
|
2014-06-26 14:49:51 +00:00
|
|
|
|
|
|
|
def minify(self):
|
2014-06-26 16:51:55 +00:00
|
|
|
return self.with_header()
|
|
|
|
|
|
|
|
def to_html(self):
|
|
|
|
if self.url:
|
2015-07-08 17:19:28 +00:00
|
|
|
try:
|
|
|
|
ira = self.registry['ir.attachment']
|
|
|
|
url = self.html_url % self.url
|
|
|
|
domain = [('type', '=', 'binary'), ('url', '=', self.url)]
|
|
|
|
with self.cr.savepoint():
|
|
|
|
ira_id = ira.search(self.cr, openerp.SUPERUSER_ID, domain, context=self.context)
|
|
|
|
if ira_id:
|
|
|
|
# TODO: update only if needed
|
|
|
|
ira.write(self.cr, openerp.SUPERUSER_ID, [ira_id], {'datas': self.content},
|
|
|
|
context=self.context)
|
|
|
|
else:
|
|
|
|
ira.create(self.cr, openerp.SUPERUSER_ID, dict(
|
|
|
|
datas=self.content.encode('utf8').encode('base64'),
|
|
|
|
mimetype='text/css',
|
|
|
|
type='binary',
|
|
|
|
name=url,
|
|
|
|
url=url,
|
|
|
|
), context=self.context)
|
|
|
|
except psycopg2.Error:
|
|
|
|
pass
|
2014-06-26 16:51:55 +00:00
|
|
|
return super(SassAsset, self).to_html()
|
2014-06-26 14:49:51 +00:00
|
|
|
|
|
|
|
def get_source(self):
|
2014-07-01 08:02:55 +00:00
|
|
|
content = textwrap.dedent(self.inline or self._fetch_content())
|
2014-06-30 16:41:29 +00:00
|
|
|
|
|
|
|
def fix_indent(m):
|
|
|
|
ind = m.group()
|
|
|
|
if self.indent is None:
|
|
|
|
self.indent = ind
|
|
|
|
if self.indent == self.reindent:
|
|
|
|
# Don't reindent the file if identation is the final one (reindent)
|
|
|
|
raise StopIteration()
|
|
|
|
return ind.replace(self.indent, self.reindent)
|
|
|
|
|
|
|
|
try:
|
|
|
|
content = self.rx_indent.sub(fix_indent, content)
|
|
|
|
except StopIteration:
|
|
|
|
pass
|
|
|
|
return "/*! %s */\n%s" % (self.id, content)
|
2014-05-08 11:51:57 +00:00
|
|
|
|
2014-04-10 10:18:47 +00:00
|
|
|
def rjsmin(script):
|
|
|
|
""" Minify js with a clever regex.
|
|
|
|
Taken from http://opensource.perlig.de/rjsmin
|
|
|
|
Apache License, Version 2.0 """
|
|
|
|
def subber(match):
|
|
|
|
""" Substitution callback """
|
|
|
|
groups = match.groups()
|
|
|
|
return (
|
|
|
|
groups[0] or
|
|
|
|
groups[1] or
|
|
|
|
groups[2] or
|
|
|
|
groups[3] or
|
|
|
|
(groups[4] and '\n') or
|
|
|
|
(groups[5] and ' ') or
|
|
|
|
(groups[6] and ' ') or
|
|
|
|
(groups[7] and ' ') or
|
|
|
|
''
|
|
|
|
)
|
2014-04-09 16:17:58 +00:00
|
|
|
|
2014-04-10 10:18:47 +00:00
|
|
|
result = re.sub(
|
|
|
|
r'([^\047"/\000-\040]+)|((?:(?:\047[^\047\\\r\n]*(?:\\(?:[^\r\n]|\r?'
|
|
|
|
r'\n|\r)[^\047\\\r\n]*)*\047)|(?:"[^"\\\r\n]*(?:\\(?:[^\r\n]|\r?\n|'
|
|
|
|
r'\r)[^"\\\r\n]*)*"))[^\047"/\000-\040]*)|(?:(?<=[(,=:\[!&|?{};\r\n]'
|
|
|
|
r')(?:[\000-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/'
|
|
|
|
r'))*((?:/(?![\r\n/*])[^/\\\[\r\n]*(?:(?:\\[^\r\n]|(?:\[[^\\\]\r\n]*'
|
|
|
|
r'(?:\\[^\r\n][^\\\]\r\n]*)*\]))[^/\\\[\r\n]*)*/)[^\047"/\000-\040]*'
|
|
|
|
r'))|(?:(?<=[\000-#%-,./:-@\[-^`{-~-]return)(?:[\000-\011\013\014\01'
|
|
|
|
r'6-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/))*((?:/(?![\r\n/*])[^/'
|
|
|
|
r'\\\[\r\n]*(?:(?:\\[^\r\n]|(?:\[[^\\\]\r\n]*(?:\\[^\r\n][^\\\]\r\n]'
|
|
|
|
r'*)*\]))[^/\\\[\r\n]*)*/)[^\047"/\000-\040]*))|(?<=[^\000-!#%&(*,./'
|
|
|
|
r':-@\[\\^`{|~])(?:[\000-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/'
|
|
|
|
r'*][^*]*\*+)*/))*(?:((?:(?://[^\r\n]*)?[\r\n]))(?:[\000-\011\013\01'
|
|
|
|
r'4\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/))*)+(?=[^\000-\040"#'
|
|
|
|
r'%-\047)*,./:-@\\-^`|-~])|(?<=[^\000-#%-,./:-@\[-^`{-~-])((?:[\000-'
|
|
|
|
r'\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)))+(?=[^'
|
|
|
|
r'\000-#%-,./:-@\[-^`{-~-])|(?<=\+)((?:[\000-\011\013\014\016-\040]|'
|
|
|
|
r'(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)))+(?=\+)|(?<=-)((?:[\000-\011\0'
|
|
|
|
r'13\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)))+(?=-)|(?:[\0'
|
|
|
|
r'00-\011\013\014\016-\040]|(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/))+|(?:'
|
|
|
|
r'(?:(?://[^\r\n]*)?[\r\n])(?:[\000-\011\013\014\016-\040]|(?:/\*[^*'
|
|
|
|
r']*\*+(?:[^/*][^*]*\*+)*/))*)+', subber, '\n%s\n' % script
|
|
|
|
).strip()
|
|
|
|
return result
|
2014-04-09 16:17:58 +00:00
|
|
|
|
2013-10-14 08:52:15 +00:00
|
|
|
# vim:et:
|