fix
[odoo/odoo.git] / openerp / addons / base / ir / ir_ui_view.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #
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.
11 #
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.
16 #
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/>.
19 #
20 ##############################################################################
21
22 from osv import fields,osv
23 from lxml import etree
24 from tools import graph
25 from tools.safe_eval import safe_eval as eval
26 import tools
27 import os
28 import logging
29
30 _logger = logging.getLogger(__name__)
31
32 class view_custom(osv.osv):
33     _name = 'ir.ui.view.custom'
34     _order = 'create_date desc'  # search(limit=1) should return the last customization
35     _columns = {
36         'ref_id': fields.many2one('ir.ui.view', 'Original View', select=True, required=True, ondelete='cascade'),
37         'user_id': fields.many2one('res.users', 'User', select=True, required=True, ondelete='cascade'),
38         'arch': fields.text('View Architecture', required=True),
39     }
40
41     def _auto_init(self, cr, context=None):
42         super(view_custom, self)._auto_init(cr, context)
43         cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'ir_ui_view_custom_user_id_ref_id\'')
44         if not cr.fetchone():
45             cr.execute('CREATE INDEX ir_ui_view_custom_user_id_ref_id ON ir_ui_view_custom (user_id, ref_id)')
46 view_custom()
47
48 class view(osv.osv):
49     _name = 'ir.ui.view'
50     _columns = {
51         'name': fields.char('View Name',size=64,  required=True),
52         'model': fields.char('Object', size=64, required=True, select=True),
53         'priority': fields.integer('Sequence', required=True),
54         'type': fields.selection((
55             ('tree','Tree'),
56             ('form','Form'),
57             ('mdx','mdx'),
58             ('graph', 'Graph'),
59             ('calendar', 'Calendar'),
60             ('diagram','Diagram'),
61             ('gantt', 'Gantt'),
62             ('kanban', 'Kanban'),
63             ('search','Search')), 'View Type', required=True, select=True),
64         'arch': fields.text('View Architecture', required=True),
65         'inherit_id': fields.many2one('ir.ui.view', 'Inherited View', ondelete='cascade', select=True),
66         'field_parent': fields.char('Child Field',size=64),
67         'xml_id': fields.function(osv.osv.get_xml_id, type='char', size=128, string="External ID",
68                                   help="ID of the view defined in xml file"),
69     }
70     _defaults = {
71         'arch': '<?xml version="1.0"?>\n<tree string="My view">\n\t<field name="name"/>\n</tree>',
72         'priority': 16
73     }
74     _order = "priority,name"
75
76     def _check_xml(self, cr, uid, ids, context=None):
77         def root_view(record):
78             if not record.inherit_id:
79                 return record
80             else:
81                 return root_view(record.inherit_id)
82         def call_view(record):
83             try:
84                 root = root_view(record)
85                 self.pool.get(root.model).fields_view_get(cr, uid, view_id=root.id, view_type=root.type, context=context)
86                 return True
87             except:
88                 _logger.exception("Can't obtain view description for model: %s (view id: %s).", record.model, record.id)
89                 return False
90         for view in self.browse(cr, uid, ids, context):
91             return call_view(view)
92
93             # TODO The following code should be executed (i.e. no early return above).
94             # TODO The view.rng file can be read only once!
95             eview = etree.fromstring(view.arch.encode('utf8'))
96             frng = tools.file_open(os.path.join('base','rng','view.rng'))
97             try:
98                 relaxng_doc = etree.parse(frng)
99                 relaxng = etree.RelaxNG(relaxng_doc)
100                 if not relaxng.validate(eview):
101                     for error in relaxng.error_log:
102                         _logger.error(tools.ustr(error))
103                     return False
104             finally:
105                 frng.close()
106         return True
107
108     _constraints = [
109         (_check_xml, 'Invalid XML for View Architecture!', ['arch'])
110     ]
111
112     def _auto_init(self, cr, context=None):
113         super(view, self)._auto_init(cr, context)
114         cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'ir_ui_view_model_type_inherit_id\'')
115         if not cr.fetchone():
116             cr.execute('CREATE INDEX ir_ui_view_model_type_inherit_id ON ir_ui_view (model, type, inherit_id)')
117
118     def get_inheriting_views_arch(self, cr, uid, view_id, model, context=None):
119         """Retrieves the architecture of views that inherit from the given view.
120
121            :param int view_id: id of the view whose inheriting views should be retrieved
122            :param str model: model identifier of the view's related model (for double-checking)
123            :rtype: list of tuples
124            :return: [(view_arch,view_id), ...]
125         """
126         cr.execute("""SELECT
127                 arch, id
128             FROM
129                 ir_ui_view
130             WHERE
131                 inherit_id=%s AND model=%s
132             ORDER BY priority""", (view_id, model))
133         return cr.fetchall()
134
135     def write(self, cr, uid, ids, vals, context=None):
136         if not isinstance(ids, (list, tuple)):
137             ids = [ids]
138         result = super(view, self).write(cr, uid, ids, vals, context)
139
140         # drop the corresponding view customizations (used for dashboards for example), otherwise
141         # not all users would see the updated views
142         custom_view_ids = self.pool.get('ir.ui.view.custom').search(cr, uid, [('ref_id','in',ids)])
143         if custom_view_ids:
144             self.pool.get('ir.ui.view.custom').unlink(cr, uid, custom_view_ids)
145
146         return result
147
148     def graph_get(self, cr, uid, id, model, node_obj, conn_obj, src_node, des_node, label, scale, context=None):
149         nodes=[]
150         nodes_name=[]
151         transitions=[]
152         start=[]
153         tres={}
154         labels={}
155         no_ancester=[]
156         blank_nodes = []
157
158         _Model_Obj=self.pool.get(model)
159         _Node_Obj=self.pool.get(node_obj)
160         _Arrow_Obj=self.pool.get(conn_obj)
161
162         for model_key,model_value in _Model_Obj._columns.items():
163                 if model_value._type=='one2many':
164                     if model_value._obj==node_obj:
165                         _Node_Field=model_key
166                         _Model_Field=model_value._fields_id
167                     flag=False
168                     for node_key,node_value in _Node_Obj._columns.items():
169                         if node_value._type=='one2many':
170                              if node_value._obj==conn_obj:
171                                  if src_node in _Arrow_Obj._columns and flag:
172                                     _Source_Field=node_key
173                                  if des_node in _Arrow_Obj._columns and not flag:
174                                     _Destination_Field=node_key
175                                     flag = True
176
177         datas = _Model_Obj.read(cr, uid, id, [],context)
178         for a in _Node_Obj.read(cr,uid,datas[_Node_Field],[]):
179             if a[_Source_Field] or a[_Destination_Field]:
180                 nodes_name.append((a['id'],a['name']))
181                 nodes.append(a['id'])
182             else:
183                 blank_nodes.append({'id': a['id'],'name':a['name']})
184
185             if a.has_key('flow_start') and a['flow_start']:
186                 start.append(a['id'])
187             else:
188                 if not a[_Source_Field]:
189                     no_ancester.append(a['id'])
190             for t in _Arrow_Obj.read(cr,uid, a[_Destination_Field],[]):
191                 transitions.append((a['id'], t[des_node][0]))
192                 tres[str(t['id'])] = (a['id'],t[des_node][0])
193                 label_string = ""
194                 if label:
195                     for lbl in eval(label):
196                         if t.has_key(tools.ustr(lbl)) and tools.ustr(t[lbl])=='False':
197                             label_string = label_string + ' '
198                         else:
199                             label_string = label_string + " " + tools.ustr(t[lbl])
200                 labels[str(t['id'])] = (a['id'],label_string)
201         g  = graph(nodes, transitions, no_ancester)
202         g.process(start)
203         g.scale(*scale)
204         result = g.result_get()
205         results = {}
206         for node in nodes_name:
207             results[str(node[0])] = result[node[0]]
208             results[str(node[0])]['name'] = node[1]
209         return {'nodes': results,
210                 'transitions': tres,
211                 'label' : labels,
212                 'blank_nodes': blank_nodes,
213                 'node_parent_field': _Model_Field,}
214 view()
215
216 class view_sc(osv.osv):
217     _name = 'ir.ui.view_sc'
218     _columns = {
219         'name': fields.char('Shortcut Name', size=64), # Kept for backwards compatibility only - resource name used instead (translatable)
220         'res_id': fields.integer('Resource Ref.', help="Reference of the target resource, whose model/table depends on the 'Resource Name' field."),
221         'sequence': fields.integer('Sequence'),
222         'user_id': fields.many2one('res.users', 'User Ref.', required=True, ondelete='cascade', select=True),
223         'resource': fields.char('Resource Name', size=64, required=True, select=True)
224     }
225
226     def _auto_init(self, cr, context=None):
227         super(view_sc, self)._auto_init(cr, context)
228         cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'ir_ui_view_sc_user_id_resource\'')
229         if not cr.fetchone():
230             cr.execute('CREATE INDEX ir_ui_view_sc_user_id_resource ON ir_ui_view_sc (user_id, resource)')
231
232     def get_sc(self, cr, uid, user_id, model='ir.ui.menu', context=None):
233         ids = self.search(cr, uid, [('user_id','=',user_id),('resource','=',model)], context=context)
234         results = self.read(cr, uid, ids, ['res_id'], context=context)
235         name_map = dict(self.pool.get(model).name_get(cr, uid, [x['res_id'] for x in results], context=context))
236         # Make sure to return only shortcuts pointing to exisintg menu items.
237         filtered_results = filter(lambda result: result['res_id'] in name_map, results)
238         for result in filtered_results:
239             result.update(name=name_map[result['res_id']])
240         return filtered_results
241
242     _order = 'sequence,name'
243     _defaults = {
244         'resource': lambda *a: 'ir.ui.menu',
245         'user_id': lambda obj, cr, uid, context: uid,
246     }
247     _sql_constraints = [
248         ('shortcut_unique', 'unique(res_id, resource, user_id)', 'Shortcut for this menu already exists!'),
249     ]
250
251 view_sc()
252
253 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
254