/
ir_ui_view.py
3030 lines (2638 loc) · 137 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
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
import collections
import functools
import inspect
import json
import logging
import pprint
import re
import uuid
import warnings
from itertools import chain
from lxml import etree
from lxml.etree import LxmlError
from lxml.builder import E
import odoo
from odoo import api, fields, models, tools, _
from odoo.exceptions import ValidationError, AccessError, UserError
from odoo.http import request
from odoo.modules.module import get_resource_from_path
from odoo.tools import config, ConstantMapping, get_diff, pycompat, apply_inheritance_specs, locate_node, str2bool
from odoo.tools import safe_eval, lazy, lazy_property, frozendict
from odoo.tools.convert import _fix_multiple_roots
from odoo.tools.misc import file_path
from odoo.tools.translate import xml_translate, TRANSLATED_ATTRS
from odoo.tools.view_validation import valid_view, get_domain_value_names, get_expression_field_names, get_dict_asts
from odoo.models import check_method_name
from odoo.osv.expression import expression
_logger = logging.getLogger(__name__)
MOVABLE_BRANDING = ['data-oe-model', 'data-oe-id', 'data-oe-field', 'data-oe-xpath', 'data-oe-source-id']
VIEW_MODIFIERS = ('column_invisible', 'invisible', 'readonly', 'required')
# Some views have a js compiler that generates an owl template from the arch. In that template,
# `__comp__` is a reserved keyword giving access to the component instance (e.g. the form renderer
# or the kanban record). However, we don't want to see implementation details leaking in archs, so
# we use the following regex to detect the use of `__comp__` in dynamic attributes, to forbid it.
COMP_REGEX = r'(^|[^\w])\s*__comp__\s*([^\w]|$)'
ref_re = re.compile(r"""
# first match 'form_view_ref' key, backrefs are used to handle single or
# double quoting of the value
(['"])(?P<view_type>\w+_view_ref)\1
# colon separator (with optional spaces around)
\s*:\s*
# open quote for value
(['"])
(?P<view_id>
# we'll just match stuff which is normally part of an xid:
# word and "." characters
[.\w]+
)
# close with same quote as opening
\3
""", re.VERBOSE)
def att_names(name):
yield name
yield f"t-att-{name}"
yield f"t-attf-{name}"
@lazy
def keep_query():
mod = odoo.addons.base.models.ir_qweb
warnings.warn(f"keep_query has been moved to {mod}", DeprecationWarning)
return mod.keep_query
class ViewCustom(models.Model):
_name = 'ir.ui.view.custom'
_description = 'Custom View'
_order = 'create_date desc' # search(limit=1) should return the last customization
_rec_name = 'user_id'
_allow_sudo_commands = False
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)
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(filepath, xmlid):
module, view_id = xmlid.split('.')
xpath = f"//*[@id='{xmlid}' or @id='{view_id}']"
# when view is created from model with inheritS of ir_ui_view, the
# xmlid has been suffixed by '_ir_ui_view'. We need to also search
# for views without this prefix.
if view_id.endswith('_ir_ui_view'):
# len('_ir_ui_view') == 11
xpath = xpath[:-1] + f" or @id='{xmlid[:-11]}' or @id='{view_id[:-11]}']"
document = etree.parse(filepath)
for node in document.xpath(xpath):
if node.tag == 'record':
field_arch = node.find('field[@name="arch"]')
if field_arch is not None:
_fix_multiple_roots(field_arch)
inner = ''.join(
etree.tostring(child, encoding='unicode')
for child in field_arch.iterchildren()
)
return field_arch.text + inner
field_view = node.find('field[@name="view_id"]')
if field_view is not None:
ref_module, _, ref_view_id = field_view.attrib.get('ref').rpartition('.')
ref_xmlid = f'{ref_module or module}.{ref_view_id}'
return get_view_arch_from_file(filepath, ref_xmlid)
return None
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'", filepath, xmlid)
return None
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)")
class View(models.Model):
_name = 'ir.ui.view'
_description = 'View'
_order = "priority,name,id"
_allow_sudo_commands = False
name = fields.Char(string='View Name', required=True)
model = fields.Char(index=True)
key = fields.Char(index='btree_not_null')
priority = fields.Integer(string='Sequence', default=16, required=True)
type = fields.Selection([('tree', 'Tree'),
('form', 'Form'),
('graph', 'Graph'),
('pivot', 'Pivot'),
('calendar', 'Calendar'),
('gantt', 'Gantt'),
('kanban', 'Kanban'),
('search', 'Search'),
('qweb', 'QWeb')], string='View Type')
arch = fields.Text(compute='_compute_arch', inverse='_inverse_arch', string='View Architecture',
help="""This field should be used when accessing view arch. It will use translation.
Note that it will read `arch_db` or `arch_fs` if in dev-xml mode.""")
arch_base = fields.Text(compute='_compute_arch_base', inverse='_inverse_arch_base', string='Base View Architecture',
help="This field is the same as `arch` field without translations")
arch_db = fields.Text(string='Arch Blob', translate=xml_translate,
help="This field stores the view arch.")
arch_fs = fields.Char(string='Arch Filename', help="""File from where the view originates.
Useful to (hard) reset broken views or to read arch from file in dev-xml mode.""")
arch_updated = fields.Boolean(string='Modified Architecture')
arch_prev = fields.Text(string='Previous View Architecture', help="""This field will save the current `arch_db` before writing on it.
Useful to (soft) reset a broken view.""")
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')
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.")
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.
""")
# The "active" field is not updated during updates if <template> is used
# instead of <record> to define the view in XML, see _tag_template. For
# qweb views, you should not rely on the active field being updated anyway
# as those views, if used in frontend layouts, can be duplicated (see COW)
# and will thus always require upgrade scripts if you really want to change
# the default value of their "active" field.
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
""")
model_id = fields.Many2one("ir.model", string="Model of the view", compute='_compute_model_id', inverse='_inverse_compute_model_id')
@api.depends('arch_db', 'arch_fs', 'arch_updated')
@api.depends_context('read_arch_from_file', 'lang', 'edit_translations', 'check_translations')
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)
lang = self.env.lang or 'en_US'
env_en = self.with_context(edit_translations=None, lang='en_US').env
env_lang = self.with_context(lang=lang).env
field_arch_db = self._fields['arch_db']
for view in self:
arch_fs = None
read_file = self._context.get('read_arch_from_file') or \
('xml' in config['dev_mode'] and not view.arch_updated)
if read_file and view.arch_fs and (view.xml_id or view.key):
xml_id = view.xml_id or view.key
# It is safe to split on / herebelow because arch_fs is explicitely stored with '/'
try:
fullpath = file_path(view.arch_fs)
except FileNotFoundError:
_logger.warning("View %s: Full path [%s] cannot be found.", xml_id, view.arch_fs)
arch_fs = False
continue
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
if arch_fs:
arch_fs = resolve_external_ids(arch_fs, xml_id).replace('%%', '%')
translation_dictionary = field_arch_db.get_translation_dictionary(
view.with_env(env_en).arch_db, {lang: view.with_env(env_lang).arch_db}
)
arch_fs = field_arch_db.translate(
lambda term: translation_dictionary[term][lang],
arch_fs
)
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])
data['arch_updated'] = False
view.write(data)
# the xml_translate will clean the arch_db when write (e.g. ('<div>') -> ('<div></div>'))
# view.arch should be reassigned here
view.arch = view.arch_db
# the field 'arch' depends on the context and has been implicitly
# modified in all languages; the invalidation below ensures that the
# field does not keep an old value in another environment
self.invalidate_recordset(['arch'])
@api.depends('arch')
@api.depends_context('read_arch_from_file')
def _compute_arch_base(self):
# 'arch_base' is the same as 'arch' without translation
for view, view_wo_lang in zip(self, self.with_context(lang=None)):
view.arch_base = view_wo_lang.arch
def _inverse_arch_base(self):
for view, view_wo_lang in zip(self, self.with_context(lang=None)):
view_wo_lang.arch = view.arch_base
def reset_arch(self, mode='soft'):
""" Reset the view arch to its previous arch (soft) or its XML file arch
if exists (hard).
"""
for view in self:
arch = False
if mode == 'soft':
arch = view.arch_prev
elif mode == 'hard' and view.arch_fs:
arch = view.with_context(read_arch_from_file=True, lang=None).arch
if arch:
# Don't save current arch in previous since we reset, this arch is probably broken
view.with_context(no_save_prev=True, lang=None).write({'arch_db': arch})
@api.depends('write_date')
def _compute_model_data_id(self):
# get the first ir_model_data record corresponding to self
for view in self:
view.model_data_id = False
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, str) 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'))]
@api.depends('model')
def _compute_model_id(self):
for record in self:
record.model_id = self.env['ir.model']._get(record.model)
def _inverse_compute_model_id(self):
for record in self:
record.model = record.model_id.model
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, node)
if WRONGCLASS.search(node.get('expr', '')):
_logger.warning(
"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, node)
return True
@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.
partial_validation = self.env.context.get('ir_ui_view_partial_validation')
self = self.with_context(validate_view_ids=(self._ids if partial_validation else True))
for view in self:
try:
# verify the view is valid xml and that the inheritance resolves
if view.inherit_id:
view_arch = etree.fromstring(view.arch)
view._valid_inheritance(view_arch)
combined_arch = view._get_combined_arch()
if view.type == 'qweb':
continue
except (etree.ParseError, ValueError) as e:
err = ValidationError(_(
"Error while parsing or validating view:\n\n%(error)s",
error=tools.ustr(e),
view=self.key or self.id,
)).with_traceback(e.__traceback__)
err.context = getattr(e, 'context', None)
raise err from None
try:
# verify that all fields used are valid, etc.
view._validate_view(combined_arch, view.model)
combined_archs = [combined_arch]
if combined_arch.xpath('//*[@attrs]') or combined_arch.xpath('//*[@states]'):
view_name = f'{view.name} ({view.xml_id})' if view.xml_id else view.name
err = ValidationError(_('Since 17.0, the "attrs" and "states" attributes are no longer used.\nView: %(name)s in %(file)s',
name=view_name, file=view.arch_fs
))
err.context = {'name': 'invalid view'}
raise err
if combined_archs[0].tag == 'data':
# A <data> element is a wrapper for multiple root nodes
combined_archs = combined_archs[0]
for view_arch in combined_archs:
for node in view_arch.xpath('//*[@__validate__]'):
del node.attrib['__validate__']
check = valid_view(view_arch, env=self.env, model=view.model)
if not check:
view_name = f'{view.name} ({view.xml_id})' if view.xml_id else view.name
raise ValidationError(_(
'Invalid view %(name)s definition in %(file)s',
name=view_name, file=view.arch_fs
))
except ValueError as e:
if hasattr(e, 'context'):
lines = etree.tostring(combined_arch, encoding='unicode').splitlines(keepends=True)
fivelines = "".join(lines[max(0, e.context["line"]-3):e.context["line"]+2])
err = ValidationError(_(
"Error while validating view near:\n\n%(fivelines)s\n%(error)s",
fivelines=fivelines, error=tools.ustr(e),
))
err.context = e.context
raise err.with_traceback(e.__traceback__) from None
else:
err = ValidationError(_(
"Error while validating view (%(view)s):\n\n%(error)s", view=self.key or self.id, error=tools.ustr(e.__context__),
))
err.context = {'name': 'invalid view'}
raise err.with_traceback(e.__context__.__traceback__) from None
return True
@api.constrains('type', 'groups_id', 'inherit_id')
def _check_groups(self):
for view in self:
if (view.groups_id and
view.inherit_id and
view.mode != 'primary'):
raise ValidationError(_("Inherited 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 methods to avoid infinite loop in `_get_combined_arch`.
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"),
]
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 'arch_db' in values and not values['arch_db']:
# delete empty arch_db to avoid triggering _check_xml before _inverse_arch_base is called
del values['arch_db']
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 not values.get('name'):
values['name'] = "%s %s" % (values.get('model'), values['type'])
# Create might be called with either `arch` (xml files), `arch_base` (form view) or `arch_db`.
values['arch_prev'] = values.get('arch_base') or values.get('arch_db') or values.get('arch')
# write on arch: bypass _inverse_arch()
if 'arch' in values:
values['arch_db'] = values.pop('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:
values['arch_fs'] = '/'.join(path_info[0:2])
values['arch_updated'] = False
values.update(self._compute_defaults(values))
self.env.registry.clear_cache('templates')
result = super(View, self.with_context(ir_ui_view_partial_validation=True)).create(vals_list)
return result.with_env(self.env)
def write(self, vals):
# Keep track if view was modified. That will be useful for the --dev mode
# to prefer modified arch over file arch.
if 'arch_updated' not in vals and ('arch' in vals or 'arch_base' in vals) and 'install_filename' not in self._context:
vals['arch_updated'] = True
# 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'].sudo().search([('ref_id', 'in', self.ids)])
if custom_view:
custom_view.unlink()
self.env.registry.clear_cache('templates')
if 'arch_db' in vals and not self.env.context.get('no_save_prev'):
vals['arch_prev'] = self.arch_db
res = super(View, self).write(self._compute_defaults(vals))
# Check the xml of the view if it gets re-activated.
# Ideally, `active` shoud have been added to the `api.constrains` of `_check_xml`,
# but the ORM writes and validates regular field (such as `active`) before inverse fields (such as `arch`),
# and therefore when writing `active` and `arch` at the same time, `_check_xml` is called twice,
# and the first time it tries to validate the view without the modification to the arch,
# which is problematic if the user corrects the view at the same time he re-enables it.
if vals.get('active'):
# Call `_validate_fields` instead of `_check_xml` to have the regular constrains error dialog
# instead of the traceback dialog.
self._validate_fields(['arch_db'])
return res
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.inherit_children_ids:
self.inherit_children_ids.unlink()
self.env.registry.clear_cache('templates')
return super(View, self).unlink()
def _update_field_translations(self, fname, translations, digest=None):
return super(View, self.with_context(no_save_prev=True))._update_field_translations(fname, translations, digest)
@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)
# 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_domain(self):
""" Return a domain to filter the sub-views to inherit from. """
return [('active', '=', True)]
@api.model
def _get_filter_xmlid_query(self):
"""This method is meant to be overridden by other modules.
"""
return """SELECT res_id FROM ir_model_data
WHERE res_id IN %(res_ids)s AND model = 'ir.ui.view' AND module IN %(modules)s
"""
def _get_inheriting_views(self):
"""
Determine the views that inherit from the current recordset, and return
them as a recordset, ordered by priority then by id.
"""
self.check_access_rights('read')
domain = self._get_inheriting_views_domain()
e = expression(domain, self.env['ir.ui.view'])
from_clause, where_clause, where_params = e.query.get_sql()
assert from_clause == '"ir_ui_view"', f"Unexpected from clause: {from_clause}"
self._flush_search(domain, fields=['inherit_id', 'priority', 'model', 'mode'])
query = f"""
WITH RECURSIVE ir_ui_view_inherits AS (
SELECT id, inherit_id, priority, mode, model
FROM ir_ui_view
WHERE id IN %s AND ({where_clause})
UNION
SELECT ir_ui_view.id, ir_ui_view.inherit_id, ir_ui_view.priority,
ir_ui_view.mode, ir_ui_view.model
FROM ir_ui_view
INNER JOIN ir_ui_view_inherits parent ON parent.id = ir_ui_view.inherit_id
WHERE coalesce(ir_ui_view.model, '') = coalesce(parent.model, '')
AND ir_ui_view.mode = 'extension'
AND ({where_clause})
)
SELECT
v.id, v.inherit_id, v.mode
FROM ir_ui_view_inherits v
ORDER BY v.priority, v.id
"""
# ORDER BY v.priority, v.id:
# 1/ sort by priority: abritrary value set by developers on some
# views to solve "dependency hell" problems and force a view
# to be combined earlier or later. e.g. all views created via
# studio have a priority=99 to be loaded last.
# 2/ sort by view id: the order the views were inserted in the
# database. e.g. base views are placed before stock ones.
self.env.cr.execute(query, [tuple(self.ids)] + where_params + where_params)
rows = self.env.cr.fetchall()
views = self.browse(row[0] for row in rows)
# optimization: fill in cache of inherit_id and mode
self.env.cache.update(views, self._fields['inherit_id'], [row[1] for row in rows])
self.env.cache.update(views, self._fields['mode'], [row[2] for row in rows])
# During an upgrade, we can only use the views that have been
# fully upgraded already.
if self.pool._init and not self._context.get('load_all_views'):
views = views._filter_loaded_views()
return views
def _filter_loaded_views(self):
"""
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.
"""
# check that all found ids have a corresponding xml_id in a loaded module
check_view_ids = self.env.context['check_view_ids']
ids_to_check = [vid for vid in self.ids if vid not in check_view_ids]
if not ids_to_check:
return self
loaded_modules = tuple(self.pool._init_modules) + (self._context.get('install_module'),)
query = self._get_filter_xmlid_query()
self.env.cr.execute(query, {'res_ids': tuple(ids_to_check), 'modules': loaded_modules})
valid_view_ids = {r[0] for r in self.env.cr.fetchall()} | set(check_view_ids)
return self.browse(vid for vid in self.ids if vid in valid_view_ids)
def _check_view_access(self):
""" Verify that a view is accessible by the current user based on the
groups attribute. Views with no groups are considered private.
"""
if self.inherit_id and self.mode != 'primary':
return self.inherit_id._check_view_access()
if self.groups_id & self.env.user.groups_id:
return True
if self.groups_id:
error = _(
"View '%(name)s' accessible only to groups %(groups)s ",
name=self.key,
groups=", ".join([g.name for g in self.groups_id]
))
else:
error = _("View '%(name)s' is private", name=self.key)
raise AccessError(error)
def _raise_view_error(self, message, node=None, *, from_exception=None, from_traceback=None):
""" Handle a view error by raising an exception.
:param str message: message to raise or log, augmented with contextual
view information
:param node: the lxml element where the error is located (if any)
:param BaseException from_exception:
when raising an exception, chain it to the provided one (default:
disable chaining)
:param types.TracebackType from_traceback:
when raising an exception, start with this traceback (default: start
at exception creation)
"""
err = ValueError(message).with_traceback(from_traceback)
err.context = {
'view': self,
'name': getattr(self, 'name', None),
'xmlid': self.env.context.get('install_xmlid') or self.xml_id,
'view.model': self.model,
'view.parent': self.inherit_id,
'file': self.env.context.get('install_filename'),
'line': node.sourceline if node is not None else 1,
}
raise err from from_exception
def _log_view_warning(self, message, node):
""" Handle a view issue by logging a warning.
:param str message: message to raise or log, augmented with contextual
view information
:param node: the lxml element where the error is located (if any)
"""
error_context = {
'view': self,
'name': getattr(self, 'name', None),
'xmlid': self.env.context.get('install_xmlid') or self.xml_id,
'view.model': self.model,
'view.parent': self.inherit_id,
'file': self.env.context.get('install_filename'),
'line': node.sourceline if node is not None else 1,
}
_logger.warning(
"%s\nView error context:\n%s",
message, pprint.pformat(error_context)
)
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
"""
return locate_node(arch, spec)
def inherit_branding(self, specs_tree):
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'):
self.inherit_branding(node)
elif node.get('t-field'):
node.set('data-oe-xpath', xpath)
self.inherit_branding(node)
else:
node.set('data-oe-id', str(self.id))
node.set('data-oe-xpath', xpath)
node.set('data-oe-model', 'ir.ui.view')
node.set('data-oe-field', 'arch')
return specs_tree
def _add_validation_flag(self, combined_arch, view=None, arch=None):
""" Add a validation flag on elements in ``combined_arch`` or ``arch``.
This is part of the partial validation of views.
:param Element combined_arch: the architecture to be modified by ``arch``
:param view: an optional view inheriting ``self``
:param Element arch: an optional modifying architecture from inheriting
view ``view``
"""
# validate_view_ids is either falsy (no validation), True (full
# validation) or a collection of ids (partial validation)
validate_view_ids = self.env.context.get('validate_view_ids')
if not validate_view_ids:
return
if validate_view_ids is True or self.id in validate_view_ids:
# optimization, flag the root node
combined_arch.set('__validate__', '1')
return
if view is None or view.id not in validate_view_ids:
return
for node in arch.xpath('//*[@position]'):
if node.get('position') in ('after', 'before', 'inside'):
# validate the elements being inserted, except the ones that
# specify a move, as in:
# <field name="foo" position="after">
# <field name="bar" position="move"/>
# </field>
for child in node.iterchildren(tag=etree.Element):
if not child.get('position'):
child.set('__validate__', '1')
if node.get('position') == 'replace':
# validate everything, since this impacts the whole arch
combined_arch.set('__validate__', '1')
break
if node.get('position') == 'attributes':
# validate the element being modified by adding
# attribute "__validate__" on it:
# <field name="foo" position="attributes">
# <attribute name="readonly">1</attribute>
# <attribute name="__validate__">1</attribute> <!-- add this -->
# </field>
node.append(E.attribute('1', name='__validate__'))
@api.model
def apply_inheritance_specs(self, source, specs_tree, pre_locate=lambda s: True):
""" 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 Element specs_tree: a modifying architecture in an inheriting view
:param (optional) pre_locate: function that is execute before locating a node.
This function receives an arch as argument.
: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).
try:
source = apply_inheritance_specs(
source, specs_tree,
inherit_branding=self._context.get('inherit_branding'),
pre_locate=pre_locate,
)
except ValueError as e:
self._raise_view_error(str(e), specs_tree)
return source
def _combine(self, hierarchy: dict):
"""
Return self's arch combined with its inherited views archs.
:param hierarchy: mapping from parent views to their child views
:return: combined architecture
:rtype: Element
"""
self.ensure_one()
assert self.mode == 'primary'
# We achieve a pre-order depth-first hierarchy traversal where
# primary views (and their children) are traversed after all the
# extensions for the current primary view have been visited.
#
# https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search_of_binary_tree
#
# Example: hierarchy = {
# 1: [2, 3], # primary view
# 1* 2: [4, 5],
# / \ 3: [],
# 2 3 4: [6], # primary view
# / \ 5: [7, 8],
# 4* 5 6: [],
# / / \ 7: [],
# 6 7 8 8: [],
# }
#
# Tree traversal order (`view` and `queue` at the `while` stmt):
# 1 [2, 3]
# 2 [5, 3, 4]
# 5 [7, 8, 3, 4]
# 7 [8, 3, 4]
# 8 [3, 4]
# 3 [4]
# 4 [6]
# 6 []
combined_arch = etree.fromstring(self.arch)
if self.env.context.get('inherit_branding'):
combined_arch.attrib.update({
'data-oe-model': 'ir.ui.view',
'data-oe-id': str(self.id),
'data-oe-field': 'arch',
})
self._add_validation_flag(combined_arch)
# The depth-first traversal is implemented with a double-ended queue.
# The queue is traversed from left to right, and after each view in the
# queue is processed, its children are pushed at the left of the queue,
# so that they are traversed in order. The queue is therefore mostly
# used as a stack. An exception is made for primary views, which are
# pushed at the other end of the queue, so that they are applied after
# all extensions have been applied.
queue = collections.deque(sorted(hierarchy[self], key=lambda v: v.mode))
while queue:
view = queue.popleft()
arch = etree.fromstring(view.arch)
if view.env.context.get('inherit_branding'):
view.inherit_branding(arch)
self._add_validation_flag(combined_arch, view, arch)
combined_arch = view.apply_inheritance_specs(combined_arch, arch)
for child_view in reversed(hierarchy[view]):
if child_view.mode == 'primary':
queue.append(child_view)
else:
queue.appendleft(child_view)
return combined_arch
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``)
"""
warnings.warn("use get_combined_arch() instead", DeprecationWarning, stacklevel=2)
if fields:
fields = list({'arch', 'model'}.union(fields))
[result] = self.read(fields)
result['arch'] = self.get_combined_arch()
return result
def get_combined_arch(self):
""" Return the arch of ``self`` (as a string) combined with its inherited views. """
return etree.tostring(self._get_combined_arch(), encoding='unicode')
def _get_combined_arch(self):
""" Return the arch of ``self`` (as an etree) combined with its inherited views. """
root = self
view_ids = []
while True:
view_ids.append(root.id)
if not root.inherit_id:
break
root = root.inherit_id
views = self.browse(view_ids)
# 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
# introduce check_view_ids in context
if 'check_view_ids' not in views.env.context:
views = views.with_context(check_view_ids=[])
views.env.context['check_view_ids'].extend(view_ids)
# Map each node to its children nodes. Note that all children nodes are
# part of a single prefetch set, which is all views to combine.
tree_views = views._get_inheriting_views()
hierarchy = collections.defaultdict(list)
for view in tree_views:
hierarchy[view.inherit_id].append(view)
# optimization: make root part of the prefetch set, too
arch = root.with_prefetch(tree_views._prefetch_ids)._combine(hierarchy)
return arch
def _get_view_refs(self, node):
""" Extract the `[view_type]_view_ref` keys and values from the node context attribute,
giving the views to use for a field node.
:param node: the field node as an etree
:return: a dictonary mapping the `[view_type]_view_ref` key to the xmlid of the view to use for that view type.
"""
if not node.get('context'):
return {}
return {
m.group('view_type'): m.group('view_id')
for m in ref_re.finditer(node.get('context'))
}
#------------------------------------------------------
# Postprocessing: translation, groups and modifiers
#------------------------------------------------------
# TODO: remove group processing from ir_qweb
#------------------------------------------------------
def postprocess_and_fields(self, node, model=None, **options):
""" Return an architecture and a description of all the fields.
The field description combines the result of fields_get() and
postprocess().
:param self: the view to postprocess
:param node: the architecture as an etree
:param model: the view's reference model name
:return: a tuple (arch, fields) where arch is the given node as a
string and fields is the description of all the fields.
"""
self and self.ensure_one() # self is at most one view
name_manager = self._postprocess_view(node, model or self.model, **options)
arch = etree.tostring(node, encoding="unicode").replace('\t', '')
models = {}
name_managers = [name_manager]
for name_manager in name_managers:
models.setdefault(name_manager.model._name, set()).update(name_manager.available_fields)
name_managers.extend(name_manager.children)
return arch, models
def _postprocess_access_rights(self, tree):
"""
Apply group restrictions: elements with a 'groups' attribute should