[FIX]:shortcuts are reverted back to their original state i.e translatable becuase...
[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 netsvc
28 import os
29 import logging
30
31 def _check_xml(self, cr, uid, ids, context=None):
32     logger = logging.getLogger('init')
33     for view in self.browse(cr, uid, ids, context):
34         eview = etree.fromstring(view.arch.encode('utf8'))
35         frng = tools.file_open(os.path.join('base','rng','view.rng'))
36         try:
37             relaxng_doc = etree.parse(frng)
38             relaxng = etree.RelaxNG(relaxng_doc)
39             if not relaxng.validate(eview):
40                 for error in relaxng.error_log:
41                     logger.error(tools.ustr(error))
42                 return False
43         finally:
44             frng.close()
45     return True
46
47 class view_custom(osv.osv):
48     _name = 'ir.ui.view.custom'
49     _order = 'create_date desc'  # search(limit=1) should return the last customization
50     _columns = {
51         'ref_id': fields.many2one('ir.ui.view', 'Original View', select=True),
52         'user_id': fields.many2one('res.users', 'User', select=True),
53         'arch': fields.text('View Architecture', required=True),
54     }
55
56     def _auto_init(self, cr, context=None):
57         super(view_custom, self)._auto_init(cr, context)
58         cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'ir_ui_view_custom_user_id_ref_id\'')
59         if not cr.fetchone():
60             cr.execute('CREATE INDEX ir_ui_view_custom_user_id_ref_id ON ir_ui_view_custom (user_id, ref_id)')
61 view_custom()
62
63 class view(osv.osv):
64     _name = 'ir.ui.view'
65     _columns = {
66         'name': fields.char('View Name',size=64,  required=True),
67         'model': fields.char('Object', size=64, required=True, select=True),
68         'priority': fields.integer('Sequence', required=True),
69         'type': fields.selection((
70             ('tree','Tree'),
71             ('form','Form'),
72             ('mdx','mdx'),
73             ('graph', 'Graph'),
74             ('calendar', 'Calendar'),
75             ('diagram','Diagram'),
76             ('gantt', 'Gantt'),
77             ('search','Search')), 'View Type', required=True, select=True),
78         'arch': fields.text('View Architecture', required=True),
79         'inherit_id': fields.many2one('ir.ui.view', 'Inherited View', ondelete='cascade', select=True),
80         'field_parent': fields.char('Child Field',size=64),
81         'xml_id': fields.function(osv.osv.get_xml_id, type='char', size=128, string="XML ID",
82                                   method=True, help="ID of the view defined in xml file"),
83     }
84     _defaults = {
85         'arch': '<?xml version="1.0"?>\n<tree string="My view">\n\t<field name="name"/>\n</tree>',
86         'priority': 16
87     }
88     _order = "priority,name"
89     _constraints = [
90         (_check_xml, 'Invalid XML for View Architecture!', ['arch'])
91     ]
92
93     def _auto_init(self, cr, context=None):
94         super(view, self)._auto_init(cr, context)
95         cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'ir_ui_view_model_type_inherit_id\'')
96         if not cr.fetchone():
97             cr.execute('CREATE INDEX ir_ui_view_model_type_inherit_id ON ir_ui_view (model, type, inherit_id)')
98
99     def write(self, cr, uid, ids, vals, context={}):
100         if not isinstance(ids, (list, tuple)):
101             ids = [ids]
102         result = super(view, self).write(cr, uid, ids, vals, context)
103
104         # drop the corresponding view customizations (used for dashboards for example), otherwise
105         # not all users would see the updated views
106         custom_view_ids = self.pool.get('ir.ui.view.custom').search(cr, uid, [('ref_id','in',ids)])
107         if custom_view_ids:
108             self.pool.get('ir.ui.view.custom').unlink(cr, uid, custom_view_ids)
109
110         return result
111
112     def graph_get(self, cr, uid, id, model, node_obj, conn_obj, src_node, des_node,label,scale,context={}):
113         if not label:
114             label = []
115         nodes=[]
116         nodes_name=[]
117         transitions=[]
118         start=[]
119         tres={}
120         labels={}
121         no_ancester=[]
122         blank_nodes = []
123
124         _Model_Obj=self.pool.get(model)
125         _Node_Obj=self.pool.get(node_obj)
126         _Arrow_Obj=self.pool.get(conn_obj)
127
128         for model_key,model_value in _Model_Obj._columns.items():
129                 if model_value._type=='one2many':
130                     if model_value._obj==node_obj:
131                         _Node_Field=model_key
132                         _Model_Field=model_value._fields_id
133                     flag=False
134                     for node_key,node_value in _Node_Obj._columns.items():
135                         if node_value._type=='one2many':
136                              if node_value._obj==conn_obj:
137                                  if src_node in _Arrow_Obj._columns and flag:
138                                     _Source_Field=node_key
139                                  if des_node in _Arrow_Obj._columns and not flag:
140                                     _Destination_Field=node_key
141                                     flag = True
142
143         datas = _Model_Obj.read(cr, uid, id, [],context)
144         for a in _Node_Obj.read(cr,uid,datas[_Node_Field],[]):
145             if a[_Source_Field] or a[_Destination_Field]:
146                 nodes_name.append((a['id'],a['name']))
147                 nodes.append(a['id'])
148             else:
149                 blank_nodes.append({'id': a['id'],'name':a['name']})
150
151             if a.has_key('flow_start') and a['flow_start']:
152                 start.append(a['id'])
153             else:
154                 if not a[_Source_Field]:
155                     no_ancester.append(a['id'])
156             for t in _Arrow_Obj.read(cr,uid, a[_Destination_Field],[]):
157                 transitions.append((a['id'], t[des_node][0]))
158                 tres[str(t['id'])] = (a['id'],t[des_node][0])
159                 label_string = ""
160                 if label:
161                     for lbl in eval(label):
162                         if t.has_key(str(lbl)) and str(t[lbl])=='False':
163                             label_string = label_string + ' '
164                         else:
165                             label_string = label_string + " " + t[lbl]
166                 labels[str(t['id'])] = (a['id'],label_string)
167         g  = graph(nodes, transitions, no_ancester)
168         g.process(start)
169         g.scale(*scale)
170         result = g.result_get()
171         results = {}
172         for node in nodes_name:
173             results[str(node[0])] = result[node[0]]
174             results[str(node[0])]['name'] = node[1]
175         return {'nodes': results,
176                 'transitions': tres,
177                 'label' : labels,
178                 'blank_nodes': blank_nodes,
179                 'node_parent_field': _Model_Field,}
180 view()
181
182 class view_sc(osv.osv):
183     _name = 'ir.ui.view_sc'
184     _columns = {
185         'name': fields.char('Shortcut Name', size=64), # Kept for backwards compatibility only - resource name used instead (translatable)
186         'res_id': fields.integer('Resource Ref.', help="Reference of the target resource, whose model/table depends on the 'Resource Name' field."),
187         'sequence': fields.integer('Sequence'),
188         'user_id': fields.many2one('res.users', 'User Ref.', required=True, ondelete='cascade', select=True),
189         'resource': fields.char('Resource Name', size=64, required=True, select=True)
190     }
191
192     def _auto_init(self, cr, context=None):
193         super(view_sc, self)._auto_init(cr, context)
194         cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = \'ir_ui_view_sc_user_id_resource\'')
195         if not cr.fetchone():
196             cr.execute('CREATE INDEX ir_ui_view_sc_user_id_resource ON ir_ui_view_sc (user_id, resource)')
197
198     def get_sc(self, cr, uid, user_id, model='ir.ui.menu', context=None):
199         ids = self.search(cr, uid, [('user_id','=',user_id),('resource','=',model)], context=context)
200         results = self.read(cr, uid, ids, ['res_id'], context=context)
201         name_map = dict(self.pool.get(model).name_get(cr, uid, [x['res_id'] for x in results], context=context))
202         # Make sure to return only shortcuts pointing to exisintg menu items.
203         filtered_results = filter(lambda result: result['res_id'] in name_map, results)
204         for result in filtered_results:
205             result.update(name=name_map[result['res_id']])
206         return filtered_results
207
208     _order = 'sequence,name'
209     _defaults = {
210         'resource': lambda *a: 'ir.ui.menu',
211         'user_id': lambda obj, cr, uid, context: uid,
212     }
213     _sql_constraints = [
214         ('shortcut_unique', 'unique(res_id, resource, user_id)', 'Shortcut for this menu already exists!'),
215     ]
216
217 view_sc()
218
219 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
220