1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
22 from lxml import etree
23 import openerp.tools as tools
24 from openerp.tools.safe_eval import safe_eval
26 from openerp.osv.orm import browse_null, browse_record
27 import openerp.pooler as pooler
29 class InheritDict(dict):
30 # Might be usefull when we're doing name lookup for call or eval.
32 def __init__(self, parent=None):
35 def __getitem__(self, name):
37 return super(InheritDict, self).__getitem__(name)
42 return self.parent[name]
45 if isinstance(val, str):
46 unicode_val = unicode(val, 'utf-8')
47 elif isinstance(val, unicode):
50 unicode_val = unicode(val)
53 class document(object):
54 def __init__(self, cr, uid, datas, func=False):
55 # create a new document
57 self.pool = pooler.get_pool(cr.dbname)
58 self.func = func or {}
63 def node_attrs_get(self, node):
68 def get_value(self, browser, field_path):
69 fields = field_path.split('.')
77 if isinstance(value, list):
81 if isinstance(value, browse_null):
86 if isinstance(value, browse_null) or (type(value)==bool and not value):
91 def get_value2(self, browser, field_path):
92 value = self.get_value(browser, field_path)
93 if isinstance(value, browse_record):
95 elif isinstance(value, browse_null):
100 def eval(self, record, expr):
101 #TODO: support remote variables (eg address.title) in expr
102 # how to do that: parse the string, find dots, replace those dotted variables by temporary
103 # "simple ones", fetch the value of those variables and add them (temporarily) to the _data
104 # dictionary passed to eval
106 #FIXME: it wont work if the data hasn't been fetched yet... this could
107 # happen if the eval node is the first one using this browse_record
108 # the next line is a workaround for the problem: it causes the resource to be loaded
109 #Pinky: Why not this ? eval(expr, browser) ?
110 # name = browser.name
111 # data_dict = browser._data[self.get_value(browser, 'id')]
112 return safe_eval(expr, {}, {'obj': record})
114 def parse_node(self, node, parent, browser, datas=None):
115 attrs = self.node_attrs_get(node)
117 if attrs['type']=='field':
118 value = self.get_value(browser, attrs['name'])
120 if value == '' and 'default' in attrs:
121 value = attrs['default']
122 el = etree.SubElement(parent, node.tag)
123 el.text = tounicode(value)
125 for key, value in attrs.iteritems():
126 if key not in ('type', 'name', 'default'):
129 elif attrs['type']=='attachment':
130 if isinstance(browser, list):
131 model = browser[0]._table_name
133 model = browser._table_name
135 value = self.get_value(browser, attrs['name'])
137 ids = self.pool.get('ir.attachment').search(self.cr, self.uid, [('res_model','=',model),('res_id','=',int(value))])
138 datas = self.pool.get('ir.attachment').read(self.cr, self.uid, ids)
141 # if there are several, pick first
143 fname = str(datas['datas_fname'])
144 ext = fname.split('.')[-1].lower()
145 if ext in ('jpg','jpeg', 'png'):
147 from StringIO import StringIO
148 dt = base64.decodestring(datas['datas'])
151 i = str(len(self.bin_datas))
152 self.bin_datas[i] = fp
153 el = etree.SubElement(parent, node.tag)
156 elif attrs['type']=='data':
158 txt = self.datas.get('form', {}).get(attrs['name'], '')
159 el = etree.SubElement(parent, node.tag)
162 elif attrs['type']=='function':
163 if attrs['name'] in self.func:
164 txt = self.func[attrs['name']](node)
166 txt = print_fnc.print_fnc(attrs['name'], node)
167 el = etree.SubElement(parent, node.tag)
170 elif attrs['type']=='eval':
171 value = self.eval(browser, attrs['expr'])
172 el = etree.SubElement(parent, node.tag)
175 elif attrs['type']=='fields':
176 fields = attrs['name'].split(',')
179 value = tuple([self.get_value2(b, f) for f in fields])
180 if not value in vals:
182 vals[value].append(b)
186 if 'order' in attrs and attrs['order']=='desc':
189 v_list = [vals[k] for k in keys]
191 el = etree.SubElement(parent, node.tag)
193 self.parse_node(el_cld, el, v)
195 elif attrs['type']=='call':
196 if len(attrs['args']):
198 # fetches the values of the variables which names where passed in the args attribute
199 args = [self.eval(browser, arg) for arg in attrs['args'].split(',')]
204 obj = self.pool.get(attrs['model'])
206 if isinstance(browser, list):
207 obj = browser[0]._table
213 ids = self.eval(browser, attrs['ids'])
215 if isinstance(browser, list):
216 ids = [b.id for b in browser]
220 # call the method itself
221 newdatas = getattr(obj, attrs['name'])(self.cr, self.uid, ids, *args)
223 def parse_result_tree(node, parent, datas):
224 if not node.tag == etree.Comment:
225 el = etree.SubElement(parent, node.tag)
226 atr = self.node_attrs_get(node)
228 if not isinstance(datas[atr['value']], (str, unicode)):
229 txt = str(datas[atr['value']])
231 txt = datas[atr['value']]
235 parse_result_tree(el_cld, el, datas)
236 if not isinstance(newdatas, list):
237 newdatas = [newdatas]
238 for newdata in newdatas:
239 parse_result_tree(node, parent, newdata)
241 elif attrs['type']=='zoom':
242 value = self.get_value(browser, attrs['name'])
244 if not isinstance(value, list):
249 el = etree.SubElement(parent, node.tag)
251 self.parse_node(el_cld, el, v)
253 # if there is no "type" attribute in the node, copy it to the xml data and parse its children
254 if not node.tag == etree.Comment:
255 if node.tag == parent.tag:
258 el = etree.SubElement(parent, node.tag)
260 self.parse_node(el_cld,el, browser)
262 return etree.tostring(self.doc,encoding="utf-8",xml_declaration=True,pretty_print=True)
264 def parse_tree(self, ids, model, context=None):
267 browser = self.pool.get(model).browse(self.cr, self.uid, ids, context)
268 self.parse_node(self.dom, self.doc, browser)
270 def parse_string(self, xml, ids, model, context=None):
273 # parses the xml template to memory
274 self.dom = etree.XML(xml)
275 # create the xml data from the xml template
276 self.parse_tree(ids, model, context)
278 def parse(self, filename, ids, model, context=None):
281 # parses the xml template to memory
282 src_file = tools.file_open(filename)
284 self.dom = etree.XML(src_file.read())
285 self.doc = etree.Element(self.dom.tag)
286 self.parse_tree(ids, model, context)
295 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: