/
ir_ui_view.py
1575 lines (1389 loc) · 77.8 KB
/
ir_ui_view.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
import collections
import copy
import datetime
import fnmatch
import logging
import os
import re
import time
import uuid
import itertools
from dateutil.relativedelta import relativedelta
from functools import partial
from operator import itemgetter
import json
import werkzeug
from lxml import etree
from lxml.etree import LxmlError
from lxml.builder import E
from odoo import api, fields, models, tools, SUPERUSER_ID, _
from odoo.exceptions import ValidationError
from odoo.http import request
from odoo.modules.module import get_resource_from_path, get_resource_path
from odoo.osv import orm
from odoo.tools import config, graph, ConstantMapping, SKIPPED_ELEMENT_TYPES, pycompat, mute_logger
from odoo.tools.convert import _fix_multiple_roots
from odoo.tools.parse_version import parse_version
from odoo.tools.safe_eval import safe_eval
from odoo.tools.view_validation import valid_view
from odoo.tools.translate import xml_translate, TRANSLATED_ATTRS
from odoo.tools.image import image_data_uri
_logger = logging.getLogger(__name__)
MOVABLE_BRANDING = ['data-oe-model', 'data-oe-id', 'data-oe-field', 'data-oe-xpath', 'data-oe-source-id']
# First sort criterion for inheritance is priority, second is chronological order of installation
# Note: natural _order has `name`, but only because that makes list browsing easier
INHERIT_ORDER = 'priority,id'
# attributes in views that may contain references to field names
ATTRS_WITH_FIELD_NAMES = {
'context',
'domain',
'decoration-bf',
'decoration-it',
'decoration-danger',
'decoration-info',
'decoration-muted',
'decoration-primary',
'decoration-success',
'decoration-warning',
}
def keep_query(*keep_params, **additional_params):
"""
Generate a query string keeping the current request querystring's parameters specified
in ``keep_params`` and also adds the parameters specified in ``additional_params``.
Multiple values query string params will be merged into a single one with comma seperated
values.
The ``keep_params`` arguments can use wildcards too, eg:
keep_query('search', 'shop_*', page=4)
"""
if not keep_params and not additional_params:
keep_params = ('*',)
params = additional_params.copy()
qs_keys = list(request.httprequest.args) if request else []
for keep_param in keep_params:
for param in fnmatch.filter(qs_keys, keep_param):
if param not in additional_params and param in qs_keys:
params[param] = request.httprequest.args.getlist(param)
return werkzeug.urls.url_encode(params)
class ViewCustom(models.Model):
_name = 'ir.ui.view.custom'
_description = 'Custom View'
_order = 'create_date desc' # search(limit=1) should return the last customization
ref_id = fields.Many2one('ir.ui.view', string='Original View', index=True, required=True, ondelete='cascade')
user_id = fields.Many2one('res.users', string='User', index=True, required=True, ondelete='cascade')
arch = fields.Text(string='View Architecture', required=True)
@api.multi
def name_get(self):
return [(rec.id, rec.user_id.name) for rec in self]
@api.model
def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
if name:
view_ids = self._search([('user_id', operator, name)] + (args or []), limit=limit, access_rights_uid=name_get_uid)
return self.browse(view_ids).name_get()
return super(ViewCustom, self)._name_search(name, args=args, operator=operator, limit=limit, name_get_uid=name_get_uid)
@api.model_cr_context
def _auto_init(self):
res = super(ViewCustom, self)._auto_init()
tools.create_index(self._cr, 'ir_ui_view_custom_user_id_ref_id',
self._table, ['user_id', 'ref_id'])
return res
def _hasclass(context, *cls):
""" Checks if the context node has all the classes passed as arguments
"""
node_classes = set(context.context_node.attrib.get('class', '').split())
return node_classes.issuperset(cls)
def get_view_arch_from_file(filename, xmlid):
doc = etree.parse(filename)
xmlid_search = (xmlid, xmlid.split('.')[1])
# when view is created from model with inheritS of ir_ui_view, the xml id has been suffixed by '_ir_ui_view'
suffix = '_ir_ui_view'
if xmlid.endswith(suffix):
xmlid_search += (xmlid.rsplit(suffix, 1)[0], xmlid.split('.')[1].rsplit(suffix, 1)[0])
for node in doc.xpath('//*[%s]' % ' or '.join(["@id='%s'" % _id for _id in xmlid_search])):
if node.tag in ('template', 'record'):
if node.tag == 'record':
field = node.find('field[@name="arch"]')
if field is None:
if node.find('field[@name="view_id"]') is not None:
view_id = node.find('field[@name="view_id"]').attrib.get('ref')
ref_id = '%s%s' % ('.' not in view_id and xmlid.split('.')[0] + '.' or '', view_id)
return get_view_arch_from_file(filename, ref_id)
else:
return None
_fix_multiple_roots(field)
inner = u''.join([etree.tostring(child, encoding='unicode') for child in field.iterchildren()])
return field.text + inner
elif node.tag == 'template':
# The following dom operations has been copied from convert.py's _tag_template()
if not node.get('inherit_id'):
node.set('t-name', xmlid)
node.tag = 't'
else:
node.tag = 'data'
node.attrib.pop('id', None)
return etree.tostring(node, encoding='unicode')
_logger.warning("Could not find view arch definition in file '%s' for xmlid '%s'", filename, xmlid_search)
return None
def add_text_before(node, text):
""" Add text before ``node`` in its XML tree. """
if text is None:
return
prev = node.getprevious()
if prev is not None:
prev.tail = (prev.tail or "") + text
else:
parent = node.getparent()
parent.text = (parent.text or "") + text
def add_text_inside(node, text):
""" Add text inside ``node``. """
if text is None:
return
if len(node):
node[-1].tail = (node[-1].tail or "") + text
else:
node.text = (node.text or "") + text
def remove_element(node):
""" Remove ``node`` but not its tail, from its XML tree. """
add_text_before(node, node.tail)
node.tail = None
node.getparent().remove(node)
xpath_utils = etree.FunctionNamespace(None)
xpath_utils['hasclass'] = _hasclass
TRANSLATED_ATTRS_RE = re.compile(r"@(%s)\b" % "|".join(TRANSLATED_ATTRS))
WRONGCLASS = re.compile(r"(@class\s*=|=\s*@class|contains\(@class)")
READONLY = re.compile(r"\breadonly\b")
class View(models.Model):
_name = 'ir.ui.view'
_description = 'View'
_order = "priority,name,id"
name = fields.Char(string='View Name', required=True)
model = fields.Char(index=True)
key = fields.Char()
priority = fields.Integer(string='Sequence', default=16, required=True)
type = fields.Selection([('tree', 'Tree'),
('form', 'Form'),
('graph', 'Graph'),
('pivot', 'Pivot'),
('calendar', 'Calendar'),
('diagram', 'Diagram'),
('gantt', 'Gantt'),
('kanban', 'Kanban'),
('search', 'Search'),
('qweb', 'QWeb')], string='View Type')
arch = fields.Text(compute='_compute_arch', inverse='_inverse_arch', string='View Architecture', nodrop=True)
arch_base = fields.Text(compute='_compute_arch_base', inverse='_inverse_arch_base', string='Base View Architecture')
arch_db = fields.Text(string='Arch Blob', translate=xml_translate, oldname='arch')
arch_fs = fields.Char(string='Arch Filename')
inherit_id = fields.Many2one('ir.ui.view', string='Inherited View', ondelete='restrict', index=True)
inherit_children_ids = fields.One2many('ir.ui.view', 'inherit_id', string='Views which inherit from this one')
field_parent = fields.Char(string='Child Field')
model_data_id = fields.Many2one('ir.model.data', string="Model Data",
compute='_compute_model_data_id', search='_search_model_data_id')
xml_id = fields.Char(string="External ID", compute='_compute_xml_id',
help="ID of the view defined in xml file")
groups_id = fields.Many2many('res.groups', 'ir_ui_view_group_rel', 'view_id', 'group_id',
string='Groups', help="If this field is empty, the view applies to all users. Otherwise, the view applies to the users of those groups only.")
model_ids = fields.One2many('ir.model.data', 'res_id', string="Models", domain=[('model', '=', 'ir.ui.view')], auto_join=True)
mode = fields.Selection([('primary', "Base view"), ('extension', "Extension View")],
string="View inheritance mode", default='primary', required=True,
help="""Only applies if this view inherits from an other one (inherit_id is not False/Null).
* if extension (default), if this view is requested the closest primary view
is looked up (via inherit_id), then all views inheriting from it with this
view's model are applied
* if primary, the closest primary view is fully resolved (even if it uses a
different model than this one), then this view's inheritance specs
(<xpath/>) are applied, and the result is used as if it were this view's
actual arch.
""")
active = fields.Boolean(default=True,
help="""If this view is inherited,
* if True, the view always extends its parent
* if False, the view currently does not extend its parent but can be enabled
""")
@api.depends('arch_db', 'arch_fs')
def _compute_arch(self):
def resolve_external_ids(arch_fs, view_xml_id):
def replacer(m):
xmlid = m.group('xmlid')
if '.' not in xmlid:
xmlid = '%s.%s' % (view_xml_id.split('.')[0], xmlid)
return m.group('prefix') + str(self.env['ir.model.data'].xmlid_to_res_id(xmlid))
return re.sub(r'(?P<prefix>[^%])%\((?P<xmlid>.*?)\)[ds]', replacer, arch_fs)
for view in self:
arch_fs = None
xml_id = view.xml_id or view.key
if 'xml' in config['dev_mode'] and view.arch_fs and xml_id:
# It is safe to split on / herebelow because arch_fs is explicitely stored with '/'
fullpath = get_resource_path(*view.arch_fs.split('/'))
if fullpath:
arch_fs = get_view_arch_from_file(fullpath, xml_id)
# replace %(xml_id)s, %(xml_id)d, %%(xml_id)s, %%(xml_id)d by the res_id
arch_fs = arch_fs and resolve_external_ids(arch_fs, xml_id).replace('%%', '%')
else:
_logger.warning("View %s: Full path [%s] cannot be found.", xml_id, view.arch_fs)
arch_fs = False
view.arch = pycompat.to_text(arch_fs or view.arch_db)
def _inverse_arch(self):
for view in self:
data = dict(arch_db=view.arch)
if 'install_filename' in self._context:
# we store the relative path to the resource instead of the absolute path, if found
# (it will be missing e.g. when importing data-only modules using base_import_module)
path_info = get_resource_from_path(self._context['install_filename'])
if path_info:
data['arch_fs'] = '/'.join(path_info[0:2])
view.write(data)
@api.depends('arch')
def _compute_arch_base(self):
# 'arch_base' is the same as 'arch' without translation
for view, view_wo_lang in pycompat.izip(self, self.with_context(lang=None)):
view.arch_base = view_wo_lang.arch
def _inverse_arch_base(self):
for view, view_wo_lang in pycompat.izip(self, self.with_context(lang=None)):
view_wo_lang.arch = view.arch_base
@api.depends('write_date')
def _compute_model_data_id(self):
# get the first ir_model_data record corresponding to self
domain = [('model', '=', 'ir.ui.view'), ('res_id', 'in', self.ids)]
for data in self.env['ir.model.data'].sudo().search_read(domain, ['res_id'], order='id desc'):
view = self.browse(data['res_id'])
view.model_data_id = data['id']
def _search_model_data_id(self, operator, value):
name = 'name' if isinstance(value, pycompat.string_types) else 'id'
domain = [('model', '=', 'ir.ui.view'), (name, operator, value)]
data = self.env['ir.model.data'].sudo().search(domain)
return [('id', 'in', data.mapped('res_id'))]
def _compute_xml_id(self):
xml_ids = collections.defaultdict(list)
domain = [('model', '=', 'ir.ui.view'), ('res_id', 'in', self.ids)]
for data in self.env['ir.model.data'].sudo().search_read(domain, ['module', 'name', 'res_id']):
xml_ids[data['res_id']].append("%s.%s" % (data['module'], data['name']))
for view in self:
view.xml_id = xml_ids.get(view.id, [''])[0]
def _valid_inheritance(self, arch):
""" Check whether view inheritance is based on translated attribute. """
for node in arch.xpath('//*[@position]'):
# inheritance may not use a translated attribute as selector
if node.tag == 'xpath':
match = TRANSLATED_ATTRS_RE.search(node.get('expr', ''))
if match:
message = "View inheritance may not use attribute %r as a selector." % match.group(1)
self.raise_view_error(message, self.id)
if WRONGCLASS.search(node.get('expr', '')):
_logger.warn(
"Error-prone use of @class in view %s (%s): use the "
"hasclass(*classes) function to filter elements by "
"their classes", self.name, self.xml_id
)
else:
for attr in TRANSLATED_ATTRS:
if node.get(attr):
message = "View inheritance may not use attribute %r as a selector." % attr
self.raise_view_error(message, self.id)
return True
def _check_groups_validity(self, view, view_name):
for node in view.xpath('//*[@groups]'):
for group in node.get('groups').replace('!', '').split(','):
if not self.env.ref(group.strip(), raise_if_not_found=False):
_logger.warning("The group %s defined in view %s does not exist!", group, view_name)
@api.constrains('arch_db')
def _check_xml(self):
# Sanity checks: the view should not break anything upon rendering!
# Any exception raised below will cause a transaction rollback.
self = self.with_context(check_field_names=True)
for view in self:
view_arch = etree.fromstring(view.arch.encode('utf-8'))
view._valid_inheritance(view_arch)
view_def = view.read_combined(['arch'])
view_arch_utf8 = view_def['arch']
if view.type != 'qweb':
view_doc = etree.fromstring(view_arch_utf8)
self._check_groups_validity(view_doc, view.name)
# verify that all fields used are valid, etc.
self.postprocess_and_fields(view.model, view_doc, view.id)
# RNG-based validation is not possible anymore with 7.0 forms
view_docs = [view_doc]
if view_docs[0].tag == 'data':
# A <data> element is a wrapper for multiple root nodes
view_docs = view_docs[0]
for view_arch in view_docs:
check = valid_view(view_arch)
if not check:
raise ValidationError(_('Invalid view %s definition in %s') % (view.name, view.arch_fs))
if check == "Warning":
_logger.warning(_('Invalid view %s definition in %s \n%s'), view.name, view.arch_fs, view.arch)
return True
@api.constrains('type', 'groups_id')
def _check_groups(self):
for view in self:
if view.type == 'qweb' and view.groups_id:
raise ValidationError(_("Qweb view cannot have 'Groups' define on the record. Use 'groups' attributes inside the view definition"))
@api.constrains('inherit_id')
def _check_000_inheritance(self):
# NOTE: constraints methods are check alphabetically. Always ensure this method will be
# called before other constraint metheods to avoid infinite loop in `read_combined`.
if not self._check_recursion(parent='inherit_id'):
raise ValidationError(_('You cannot create recursive inherited views.'))
_sql_constraints = [
('inheritance_mode',
"CHECK (mode != 'extension' OR inherit_id IS NOT NULL)",
"Invalid inheritance mode: if the mode is 'extension', the view must"
" extend an other view"),
('qweb_required_key',
"CHECK (type != 'qweb' OR key IS NOT NULL)",
"Invalid key: QWeb view should have a key"),
]
@api.model_cr_context
def _auto_init(self):
res = super(View, self)._auto_init()
tools.create_index(self._cr, 'ir_ui_view_model_type_inherit_id',
self._table, ['model', 'inherit_id'])
return res
def _compute_defaults(self, values):
if 'inherit_id' in values:
# Do not automatically change the mode if the view already has an inherit_id,
# and the user change it to another.
if not values['inherit_id'] or all(not view.inherit_id for view in self):
values.setdefault('mode', 'extension' if values['inherit_id'] else 'primary')
return values
@api.model_create_multi
def create(self, vals_list):
for values in vals_list:
if not values.get('type'):
if values.get('inherit_id'):
values['type'] = self.browse(values['inherit_id']).type
else:
try:
if not values.get('arch') and not values.get('arch_base'):
raise ValidationError(_('Missing view architecture.'))
values['type'] = etree.fromstring(values.get('arch') or values.get('arch_base')).tag
except LxmlError:
# don't raise here, the constraint that runs `self._check_xml` will
# do the job properly.
pass
if not values.get('key') and values.get('type') == 'qweb':
values['key'] = "gen_key.%s" % str(uuid.uuid4())[:6]
if values.get('model'):
values['key'] = "%s.gen_key_%s" % (values.get('model'), str(uuid.uuid4())[:6])
if not values.get('name'):
values['name'] = "%s %s" % (values.get('model'), values['type'])
values.update(self._compute_defaults(values))
self.clear_caches()
return super(View, self).create(vals_list)
@api.multi
def write(self, vals):
# If view is modified we remove the arch_fs information thus activating the arch_db
# version. An `init` of the view will restore the arch_fs for the --dev mode
if ('arch' in vals or 'arch_base' in vals) and 'install_filename' not in self._context:
vals['arch_fs'] = False
# drop the corresponding view customizations (used for dashboards for example), otherwise
# not all users would see the updated views
custom_view = self.env['ir.ui.view.custom'].search([('ref_id', 'in', self.ids)])
if custom_view:
custom_view.unlink()
self.clear_caches()
return super(View, self).write(self._compute_defaults(vals))
def unlink(self):
# if in uninstall mode and has children views, emulate an ondelete cascade
if self.env.context.get('_force_unlink', False) and self.mapped('inherit_children_ids'):
self.mapped('inherit_children_ids').unlink()
super(View, self).unlink()
@api.multi
@api.returns('self', lambda value: value.id)
def copy(self, default=None):
self.ensure_one()
if self.key and default and 'key' not in default:
new_key = self.key + '_%s' % str(uuid.uuid4())[:6]
default = dict(default or {}, key=new_key)
return super(View, self).copy(default)
@api.multi
def toggle(self):
""" Switches between enabled and disabled statuses
"""
for view in self:
view.write({'active': not view.active})
# default view selection
@api.model
def default_view(self, model, view_type):
""" Fetches the default view for the provided (model, view_type) pair:
primary view with the lowest priority.
:param str model:
:param int view_type:
:return: id of the default view of False if none found
:rtype: int
"""
domain = [('model', '=', model), ('type', '=', view_type), ('mode', '=', 'primary')]
return self.search(domain, limit=1).id
#------------------------------------------------------
# Inheritance mecanism
#------------------------------------------------------
@api.model
def _get_inheriting_views_arch_domain(self, view_id, model):
return [
['inherit_id', '=', view_id],
['model', '=', model],
['mode', '=', 'extension'],
['active', '=', True],
]
@api.model
def get_inheriting_views_arch(self, view_id, model):
"""Retrieves the architecture of views that inherit from the given view, from the sets of
views that should currently be used in the system. During the module upgrade phase it
may happen that a view is present in the database but the fields it relies on are not
fully loaded yet. This method only considers views that belong to modules whose code
is already loaded. Custom views defined directly in the database are loaded only
after the module initialization phase is completely finished.
:param int view_id: id of the view whose inheriting views should be retrieved
:param str model: model identifier of the inheriting views.
:rtype: list of tuples
:return: [(view_arch,view_id), ...]
"""
user_groups = self.env.user.groups_id
conditions = self._get_inheriting_views_arch_domain(view_id, model)
if self.pool._init and not self._context.get('load_all_views'):
# Module init currently in progress, only consider views from
# modules whose code is already loaded
# Search terms inside an OR branch in a domain
# cannot currently use relationships that are
# not required. The root cause is the INNER JOIN
# used to implement it.
modules = tuple(self.pool._init_modules) + (self._context.get('install_module'),)
views = self.search(conditions + [('model_ids.module', 'in', modules)])
views_cond = [('id', 'in', list(self._context.get('check_view_ids') or (0,)) + views.ids)]
views = self.search(conditions + views_cond, order=INHERIT_ORDER)
else:
views = self.search(conditions, order=INHERIT_ORDER)
return [(view.arch, view.id)
for view in views.sudo()
if not view.groups_id or (view.groups_id & user_groups)]
@api.model
def raise_view_error(self, message, view_id):
view = self.browse(view_id)
not_avail = _('n/a')
message = (
"%(msg)s\n\n" +
_("Error context:\nView `%(view_name)s`") +
"\n[view_id: %(viewid)s, xml_id: %(xmlid)s, "
"model: %(model)s, parent_id: %(parent)s]"
) % {
'view_name': view.name or not_avail,
'viewid': view_id or not_avail,
'xmlid': view.xml_id or not_avail,
'model': view.model or not_avail,
'parent': view.inherit_id.id or not_avail,
'msg': message,
}
_logger.info(message)
raise ValueError(message)
def locate_node(self, arch, spec):
""" Locate a node in a source (parent) architecture.
Given a complete source (parent) architecture (i.e. the field
`arch` in a view), and a 'spec' node (a node in an inheriting
view that specifies the location in the source view of what
should be changed), return (if it exists) the node in the
source view matching the specification.
:param arch: a parent architecture to modify
:param spec: a modifying node in an inheriting view
:return: a node in the source matching the spec
"""
if spec.tag == 'xpath':
nodes = etree.ETXPath(spec.get('expr'))(arch)
return nodes[0] if nodes else None
elif spec.tag == 'field':
# Only compare the field name: a field can be only once in a given view
# at a given level (and for multilevel expressions, we should use xpath
# inheritance spec anyway).
for node in arch.iter('field'):
if node.get('name') == spec.get('name'):
return node
return None
for node in arch.iter(spec.tag):
if isinstance(node, SKIPPED_ELEMENT_TYPES):
continue
if all(node.get(attr) == spec.get(attr) for attr in spec.attrib
if attr not in ('position', 'version')):
# Version spec should match parent's root element's version
if spec.get('version') and spec.get('version') != arch.get('version'):
return None
return node
return None
def inherit_branding(self, specs_tree, view_id, root_id):
for node in specs_tree.iterchildren(tag=etree.Element):
xpath = node.getroottree().getpath(node)
if node.tag == 'data' or node.tag == 'xpath' or node.get('position') or node.get('t-field'):
self.inherit_branding(node, view_id, root_id)
else:
node.set('data-oe-id', str(view_id))
node.set('data-oe-xpath', xpath)
node.set('data-oe-model', 'ir.ui.view')
node.set('data-oe-field', 'arch')
return specs_tree
@api.model
def apply_inheritance_specs(self, source, specs_tree, inherit_id):
""" Apply an inheriting view (a descendant of the base view)
Apply to a source architecture all the spec nodes (i.e. nodes
describing where and what changes to apply to some parent
architecture) given by an inheriting view.
:param Element source: a parent architecture to modify
:param Elepect specs_tree: a modifying architecture in an inheriting view
:param inherit_id: the database id of specs_arch
:return: a modified source where the specs are applied
:rtype: Element
"""
# Queue of specification nodes (i.e. nodes describing where and
# changes to apply to some parent architecture).
specs = [specs_tree]
def extract(spec):
"""
Utility function that locates a node given a specification, remove
it from the source and returns it.
"""
if len(spec):
self.raise_view_error(_("Invalid specification for moved nodes: '%s'") %
etree.tostring(spec), inherit_id)
to_extract = self.locate_node(source, spec)
if to_extract is not None:
remove_element(to_extract)
return to_extract
else:
self.raise_view_error(_("Element '%s' cannot be located in parent view") %
etree.tostring(spec), inherit_id)
while len(specs):
spec = specs.pop(0)
if isinstance(spec, SKIPPED_ELEMENT_TYPES):
continue
if spec.tag == 'data':
specs += [c for c in spec]
continue
node = self.locate_node(source, spec)
if node is not None:
pos = spec.get('position', 'inside')
if pos == 'replace':
for loc in spec.xpath(".//*[text()='$0']"):
loc.text = ''
loc.append(copy.deepcopy(node))
if node.getparent() is None:
source = copy.deepcopy(spec[0])
else:
for child in spec:
if child.get('position') == 'move':
child = extract(child)
node.addprevious(child)
node.getparent().remove(node)
elif pos == 'attributes':
for child in spec.getiterator('attribute'):
attribute = child.get('name')
value = child.text or ''
if child.get('add') or child.get('remove'):
assert not child.text
separator = child.get('separator', ',')
if separator == ' ':
separator = None # squash spaces
to_add = (
s for s in (s.strip() for s in child.get('add', '').split(separator))
if s
)
to_remove = {s.strip() for s in child.get('remove', '').split(separator)}
values = (s.strip() for s in node.get(attribute, '').split(separator))
value = (separator or ' ').join(itertools.chain(
(v for v in values if v not in to_remove),
to_add
))
if value:
node.set(attribute, value)
elif attribute in node.attrib:
del node.attrib[attribute]
elif pos == 'inside':
add_text_inside(node, spec.text)
for child in spec:
if child.get('position') == 'move':
child = extract(child)
node.append(child)
elif pos == 'after':
# add a sentinel element right after node, insert content of
# spec before the sentinel, then remove the sentinel element
sentinel = E.sentinel()
node.addnext(sentinel)
add_text_before(sentinel, spec.text)
for child in spec:
if child.get('position') == 'move':
child = extract(child)
sentinel.addprevious(child)
remove_element(sentinel)
elif pos == 'before':
add_text_before(node, spec.text)
for child in spec:
if child.get('position') == 'move':
child = extract(child)
node.addprevious(child)
else:
self.raise_view_error(_("Invalid position attribute: '%s'") % pos, inherit_id)
else:
attrs = ''.join([
' %s="%s"' % (attr, spec.get(attr))
for attr in spec.attrib
if attr != 'position'
])
tag = "<%s%s>" % (spec.tag, attrs)
self.raise_view_error(_("Element '%s' cannot be located in parent view") % tag, inherit_id)
return source
@api.model
def apply_view_inheritance(self, source, source_id, model, root_id=None):
""" Apply all the (directly and indirectly) inheriting views.
:param source: a parent architecture to modify (with parent modifications already applied)
:param source_id: the database view_id of the parent view
:param model: the original model for which we create a view (not
necessarily the same as the source's model); only the inheriting
views with that specific model will be applied.
:return: a modified source where all the modifying architecture are applied
"""
if root_id is None:
root_id = source_id
sql_inherit = self.get_inheriting_views_arch(source_id, model)
for (specs, view_id) in sql_inherit:
specs_tree = etree.fromstring(specs.encode('utf-8'))
if self._context.get('inherit_branding'):
self.inherit_branding(specs_tree, view_id, root_id)
source = self.apply_inheritance_specs(source, specs_tree, view_id)
source = self.apply_view_inheritance(source, view_id, model, root_id=root_id)
return source
@api.multi
def read_combined(self, fields=None):
"""
Utility function to get a view combined with its inherited views.
* Gets the top of the view tree if a sub-view is requested
* Applies all inherited archs on the root view
* Returns the view with all requested fields
.. note:: ``arch`` is always added to the fields list even if not
requested (similar to ``id``)
"""
# introduce check_view_ids in context
if 'check_view_ids' not in self._context:
self = self.with_context(check_view_ids=[])
check_view_ids = self._context['check_view_ids']
# if view_id is not a root view, climb back to the top.
root = self
while root.mode != 'primary':
# Add inherited views to the list of loading forced views
# Otherwise, inherited views could not find elements created in their direct parents if that parent is defined in the same module
check_view_ids.append(root.id)
root = root.inherit_id
# arch and model fields are always returned
if fields:
fields = list({'arch', 'model'}.union(fields))
# read the view arch
[view_data] = root.read(fields=fields)
view_arch = etree.fromstring(view_data['arch'].encode('utf-8'))
if not root.inherit_id:
arch_tree = view_arch
else:
parent_view = root.inherit_id.read_combined(fields=fields)
arch_tree = etree.fromstring(parent_view['arch'])
arch_tree = self.apply_inheritance_specs(arch_tree, view_arch, parent_view['id'])
if self._context.get('inherit_branding'):
arch_tree.attrib.update({
'data-oe-model': 'ir.ui.view',
'data-oe-id': str(root.id),
'data-oe-field': 'arch',
})
# and apply inheritance
arch = self.apply_view_inheritance(arch_tree, root.id, self.model)
return dict(view_data, arch=etree.tostring(arch, encoding='unicode'))
def _apply_group(self, model, node, modifiers, fields):
"""Apply group restrictions, may be set at view level or model level::
* at view level this means the element should be made invisible to
people who are not members
* at model level (exclusively for fields, obviously), this means
the field should be completely removed from the view, as it is
completely unavailable for non-members
:return: True if field should be included in the result of fields_view_get
"""
Model = self.env[model]
if node.tag == 'field' and node.get('name') in Model._fields:
field = Model._fields[node.get('name')]
if field.groups and not self.user_has_groups(groups=field.groups):
node.getparent().remove(node)
fields.pop(node.get('name'), None)
# no point processing view-level ``groups`` anymore, return
return False
if node.get('groups'):
can_see = self.user_has_groups(groups=node.get('groups'))
if not can_see:
node.set('invisible', '1')
modifiers['invisible'] = True
if 'attrs' in node.attrib:
del node.attrib['attrs'] # avoid making field visible later
del node.attrib['groups']
return True
#------------------------------------------------------
# Postprocessing: translation, groups and modifiers
#------------------------------------------------------
# TODO: remove group processing from ir_qweb
#------------------------------------------------------
@api.model
def postprocess(self, model, node, view_id, in_tree_view, model_fields):
"""Return the description of the fields in the node.
In a normal call to this method, node is a complete view architecture
but it is actually possible to give some sub-node (this is used so
that the method can call itself recursively).
Originally, the field descriptions are drawn from the node itself.
But there is now some code calling fields_get() in order to merge some
of those information in the architecture.
"""
result = False
fields = {}
children = True
modifiers = {}
if model not in self.env:
self.raise_view_error(_('Model not found: %(model)s') % dict(model=model), view_id)
Model = self.env[model]
if node.tag in ('field', 'node', 'arrow'):
if node.get('object'):
attrs = {}
views = {}
xml_form = E.form(*(f for f in node if f.tag == 'field'))
xarch, xfields = self.with_context(base_model_name=model).postprocess_and_fields(node.get('object'), xml_form, view_id)
views['form'] = {
'arch': xarch,
'fields': xfields,
}
attrs = {'views': views}
fields = xfields
if node.get('name'):
attrs = {}
field = Model._fields.get(node.get('name'))
if field:
editable = self.env.context.get('view_is_editable', True) and self._field_is_editable(field, node)
children = False
views = {}
for f in node:
if f.tag in ('form', 'tree', 'graph', 'kanban', 'calendar'):
node.remove(f)
xarch, xfields = self.with_context(
base_model_name=model,
view_is_editable=editable,
).postprocess_and_fields(field.comodel_name, f, view_id)
views[str(f.tag)] = {
'arch': xarch,
'fields': xfields,
}
attrs = {'views': views}
if field.comodel_name in self.env and field.type in ('many2one', 'many2many'):
Comodel = self.env[field.comodel_name]
node.set('can_create', 'true' if Comodel.check_access_rights('create', raise_exception=False) else 'false')
node.set('can_write', 'true' if Comodel.check_access_rights('write', raise_exception=False) else 'false')
fields[node.get('name')] = attrs
field = model_fields.get(node.get('name'))
if field:
orm.transfer_field_to_modifiers(field, modifiers)
elif node.tag in ('form', 'tree'):
result = Model.view_header_get(False, node.tag)
if result:
node.set('string', result)
in_tree_view = node.tag == 'tree'
elif node.tag == 'calendar':
for additional_field in ('date_start', 'date_delay', 'date_stop', 'color', 'all_day'):
if node.get(additional_field):
fields[node.get(additional_field).split('.', 1)[0]] = {}
for f in node:
if f.tag == 'filter':
fields[f.get('name')] = {}
if not self._apply_group(model, node, modifiers, fields):
# node must be removed, no need to proceed further with its children
return fields
# The view architeture overrides the python model.
# Get the attrs before they are (possibly) deleted by check_group below
orm.transfer_node_to_modifiers(node, modifiers, self._context, in_tree_view)
for f in node:
if children or (node.tag == 'field' and f.tag in ('filter', 'separator')):
fields.update(self.postprocess(model, f, view_id, in_tree_view, model_fields))
orm.transfer_modifiers_to_node(modifiers, node)
return fields
def add_on_change(self, model_name, arch):
""" Add attribute on_change="1" on fields that are dependencies of
computed fields on the same view.
"""
# map each field object to its corresponding nodes in arch
field_nodes = collections.defaultdict(list)
def collect(node, model):
if node.tag == 'field':
field = model._fields.get(node.get('name'))
if field:
field_nodes[field].append(node)
if field.relational:
model = self.env[field.comodel_name]
for child in node:
collect(child, model)
collect(arch, self.env[model_name])
for field, nodes in field_nodes.items():
# if field should trigger an onchange, add on_change="1" on the
# nodes referring to field
model = self.env[field.model_name]
if model._has_onchange(field, field_nodes):
for node in nodes:
if not node.get('on_change'):
node.set('on_change', '1')
return arch
def _view_is_editable(self, node):
""" Return whether the node is an editable view. """
return node.tag == 'form' or node.tag == 'tree' and node.get('editable')
def _field_is_editable(self, field, node):
""" Return whether a field is editable (not always readonly). """
return (
(not field.readonly or READONLY.search(str(field.states or ""))) and
(node.get('readonly') != "1" or READONLY.search(node.get('attrs') or ""))
)
def get_attrs_symbols(self):
""" Return a set of predefined symbols for evaluating attrs. """
return {
'True', 'False', 'None', # those are identifiers in Python 2.7
'self',
'parent',
'id',
'uid',
'context',
'context_today',
'active_id',
'active_ids',
'active_model',
'time',
'datetime',
'relativedelta',
'current_date',
'abs',
'len',
'bool',
'float',
'str',
'unicode',
}
def get_attrs_field_names(self, arch, model, editable):
""" Retrieve the field names appearing in context, domain and attrs, and
return a list of triples ``(field_name, attr_name, attr_value)``.
"""
VIEW_TYPES = {item[0] for item in type(self).type.selection}
symbols = self.get_attrs_symbols() | {None}
result = []
def get_name(node):
""" return the name from an AST node, or None """
if isinstance(node, ast.Name):
return node.id
def get_subname(get, node):
""" return the subfield name from an AST node, or None """
if isinstance(node, ast.Attribute) and get(node.value) == 'parent':
return node.attr
def process_expr(expr, get, key, val):
""" parse `expr` and collect triples """
for node in ast.walk(ast.parse(expr.strip(), mode='eval')):
name = get(node)