# This file is part of Tryton. The COPYRIGHT file at the top level of # this repository contains the full copyright notices and license terms. from lxml import etree from functools import wraps import copy import collections from trytond.exceptions import UserError from trytond.i18n import gettext from trytond.model import Model, fields from trytond.tools import ClassProperty, is_instance_method from trytond.pyson import PYSONDecoder, PYSONEncoder from trytond.transaction import Transaction from trytond.cache import Cache from trytond.pool import Pool from trytond.rpc import RPC from .fields import on_change_result __all__ = ['ModelView'] class AccessButtonError(UserError): pass def _find(tree, element): if element.tag == 'xpath': res = tree.xpath(element.get('expr')) if res: return res[0] return None def _inherit_apply(tree, inherit): root_inherit = inherit.getroottree().getroot() for element2 in root_inherit: if element2.tag != 'xpath': continue element = _find(tree, element2) if element is not None: pos = element2.get('position', 'inside') if pos == 'replace': parent = element.getparent() if parent is None: tree, = element2 continue enext = element.getnext() if enext is not None: for child in element2: index = parent.index(enext) parent.insert(index, child) else: parent.extend(list(element2)) parent.remove(element) elif pos == 'replace_attributes': child = element2[0] for attr in child.attrib: element.set(attr, child.get(attr)) elif pos == 'inside': element.extend(list(element2)) elif pos == 'after': parent = element.getparent() enext = element.getnext() if enext is not None: for child in list(element2): index = parent.index(enext) parent.insert(index, child) else: parent.extend(list(element2)) elif pos == 'before': parent = element.getparent() for child in list(element2): index = parent.index(element) parent.insert(index, child) else: raise AttributeError( 'Unknown position in inherited view %s!' % pos) else: raise AttributeError( 'Couldn\'t find tag (%s: %s) in parent view!' % (element2.tag, element2.get('expr'))) return tree def on_change(func): @wraps(func) def wrapper(self, *args, **kwargs): result = func(self, *args, **kwargs) assert result is None, func return self wrapper.on_change = True return wrapper class ModelView(Model): """ Define a model with views in Tryton. """ __modules_list = None # Cache for the modules list sorted by dependency _fields_view_get_cache = Cache('modelview.fields_view_get') _view_toolbar_get_cache = Cache('modelview.view_toolbar_get') @staticmethod def _reset_modules_list(): ModelView.__modules_list = None @ClassProperty @classmethod def _modules_list(cls): from trytond.modules import create_graph, get_module_list if ModelView.__modules_list: return ModelView.__modules_list graph = create_graph(get_module_list()) ModelView.__modules_list = [x.name for x in graph] + [None] return ModelView.__modules_list @classmethod def __setup__(cls): super(ModelView, cls).__setup__() cls.__rpc__['fields_view_get'] = RPC() cls.__rpc__['view_toolbar_get'] = RPC() cls.__rpc__['on_change'] = RPC(instantiate=0) cls.__rpc__['on_change_with'] = RPC(instantiate=0) cls._buttons = {} fields_ = {} callables = {} for name in dir(cls): if name.startswith('__'): continue attr = getattr(cls, name) if isinstance(attr, fields.Field): fields_[name] = attr elif callable(attr): callables[name] = attr methods = { '_done': set(), 'depends': collections.defaultdict(set), 'depend_methods': collections.defaultdict(set), 'change': collections.defaultdict(set), } cls.__change_buttons = methods['change'] def set_methods(name): if name in methods['_done']: return methods['_done'].add(name) for parent_cls in cls.__mro__: parent_meth = getattr(parent_cls, name, None) if not parent_meth: continue for attr in ['depends', 'depend_methods', 'change']: parent_value = getattr(parent_meth, attr, None) if parent_value: methods[attr][name] |= parent_value def setup_field(field_name, field, attribute): if attribute == 'selection_change_with': if isinstance( getattr(field, 'selection', None), str): function_name = field.selection else: return else: function_name = '%s_%s' % (attribute, field_name) function = getattr(cls, function_name, None) if not function: return set_methods(function_name) setattr(field, attribute, methods['depends'][function_name]) meth_names = list(methods['depend_methods'][function_name]) meth_done = set() while meth_names: meth_name = meth_names.pop() assert callable(getattr(cls, meth_name)), \ "%s.%s not callable" % (cls, meth_name) set_methods(meth_name) setattr(field, attribute, getattr(field, attribute) | methods['depends'][meth_name]) meth_names += list( methods['depend_methods'][meth_name] - meth_done) meth_done.add(meth_name) if (attribute == 'on_change' and not getattr(function, 'on_change', None)): # Decorate on_change to always return self setattr(cls, function_name, on_change(function)) for name, field in fields_.items(): for attribute in [ 'on_change', 'on_change_with', 'autocomplete', 'selection_change_with', ]: setup_field(name, field, attribute) @classmethod def __post_setup__(cls): super(ModelView, cls).__post_setup__() # Update __rpc__ for field_name, field in cls._fields.items(): field.set_rpc(cls) for button in cls._buttons: if not is_instance_method(cls, button): cls.__rpc__.setdefault(button, RPC(readonly=False, instantiate=0)) else: cls.__rpc__.setdefault(button, RPC(instantiate=0, result=on_change_result)) @classmethod def fields_view_get(cls, view_id=None, view_type='form'): ''' Return a view definition. If view_id is None the first one will be used of view_type. The definition is a dictionary with keys: - model: the model name - type: the type of the view - view_id: the id of the view - arch: the xml description of the view - fields: a dictionary with the definition of each field in the view - field_childs: the name of the childs field for tree ''' key = (cls.__name__, view_id, view_type) result = cls._fields_view_get_cache.get(key) if result: return result result = {'model': cls.__name__} pool = Pool() View = pool.get('ir.ui.view') view = None inherit_view_id = None if view_id: view = View(view_id) else: domain = [ ('model', '=', cls.__name__), ['OR', ('inherit', '=', None), ('inherit.model', '!=', cls.__name__), ], ] views = View.search(domain) views = [v for v in views if v.rng_type == view_type] if views: view = views[0] if view: if view.inherit: inherit_view_id = view.id view = view.inherit # if a view was found if view: result['type'] = view.rng_type result['view_id'] = view_id result['arch'] = view.arch result['field_childs'] = view.field_childs # Check if view is not from an inherited model if view.model != cls.__name__: Inherit = pool.get(view.model) result['arch'] = Inherit.fields_view_get(view.id)['arch'] real_view_id = inherit_view_id else: real_view_id = view.id # get all views which inherit from (ie modify) this view views = View.search([ 'OR', [ ('inherit', '=', real_view_id), ('model', '=', cls.__name__), ], [ ('id', '=', real_view_id), ('inherit', '!=', None), ], ]) raise_p = False while True: try: views.sort(key=lambda x: cls._modules_list.index(x.module or None)) break except ValueError: if raise_p: raise # There is perhaps a new module in the directory ModelView._reset_modules_list() raise_p = True parser = etree.XMLParser(remove_comments=True) tree = etree.fromstring(result['arch'], parser=parser) for view in views: if view.domain: if not PYSONDecoder({'context': Transaction().context} ).decode(view.domain): continue if not view.arch or not view.arch.strip(): continue tree_inherit = etree.fromstring(view.arch, parser=parser) tree = _inherit_apply(tree, tree_inherit) result['arch'] = etree.tostring( tree, encoding='utf-8').decode('utf-8') # otherwise, build some kind of default view else: if view_type == 'form': res = cls.fields_get() xml = '''''' \ '''
''' for i in res: if i in ('create_uid', 'create_date', 'write_uid', 'write_date', 'id', 'rec_name'): continue if res[i]['type'] not in ('one2many', 'many2many'): xml += '