xsd2uicfg.py 9.11 KB
Newer Older
1
# copyright 2016-2017 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# contact http://www.logilab.fr -- mailto:contact@logilab.fr
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
"""Generate CubicWeb's uicfg rules from XSD file.

XSD parsing is done using generateDS, which has been copied into the `gends` directory (only the
used bits).
"""

22
23
from six import text_type

24
from cubicweb import neg_role, _
25

26
from xsd import XSDM_MAPPING
27
from xsd2yams import CodeGenerator
28
29


30
31
FIRST_LEVEL_ETYPES = set(('SEDAArchiveTransfer',
                          'SEDABinaryDataObject', 'SEDAPhysicalDataObject',
32
                          'SEDAArchiveUnit'))
33

34
35
36
RTYPES_IN_TAB = set((
    'seda_binary_data_object',
    'seda_physical_data_object',
37
    'seda_related_transfer_reference',
38
    'seda_archive_unit',
39
    'seda_relationship',
40
41
42
43
44
45
46
    'seda_storage_rule',
    'seda_appraisal_rule',
    'seda_access_rule',
    'seda_dissemination_rule',
    'seda_reuse_rule',
    'seda_classification_rule',
    'seda_need_authorization',
47
48
49
    'seda_restriction_rule_id_ref',
    'seda_restriction_value',
    'seda_restriction_end_date',
50
))
51
for element_name in ('CodeListVersions', 'FormatIdentification', 'FileInfo', 'PhysicalDimensions',
52
                     'Gps', 'RelatedObjectReference', 'CustodialHistory', 'Coverage'):
53
54
    for rtype, role, path in XSDM_MAPPING.iter_rtype_role(element_name):
        RTYPES_IN_TAB.add(rtype)
55

56

57
58
59
class UICFGGenerator(CodeGenerator):
    """UICFG rules generator"""

60
    rtags_info = {
61
62
63
64
65
        'actionbox_appearsin_addmenu': {
            'shortname': 'abaa',
            'subject': "abaa.tag_subject_of(('*', '{rtype}', '*'), {value})",
            'object': "abaa.tag_object_of(('*', '{rtype}', '*'), {value})",
        },
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
        'autoform_section': {
            'shortname': 'afs',
            'subject': "afs.tag_subject_of(('*', '{rtype}', '*'), 'main', '{value}')",
            'object': "afs.tag_object_of(('*', '{rtype}', '*'), 'main', '{value}')",
        },
        'autoform_field_kwargs': {
            'shortname': 'affk',
            'subject': "affk.tag_subject_of(('*', '{rtype}', '*'), {value})",
            'object': "affk.tag_object_of(('*', '{rtype}', '*'), {value})",
        },
        'primaryview_section': {
            'shortname': 'pvs',
            'subject': "pvs.tag_subject_of(('*', '{rtype}', '*'), '{value}')",
            'object': "pvs.tag_object_of(('*', '{rtype}', '*'), '{value}')",
        },
81
82
83
        'reledit_ctrl': {
            'shortname': 'rec',
            'subject': "rec.tag_subject_of(('*', '{rtype}', '*'), "
84
            "{{'novalue_label': '{value}'}})",
85
            'object': "rec.tag_object_of(('*', '{rtype}', '*'), "
86
            "{{'novalue_label': '{value}'}})",
87
        },
88
    }
89

90
    def _generate(self, mapping, stream):
91
        self._processed = set()
92
        stream.write('from cubicweb.web import formwidgets as fw\n')
93
94
95
96
97
98
99
        stream.write('from cubicweb.web.views import uicfg\n\n')
        # indexview_etype_section configuration
        stream.write('ives = uicfg.indexview_etype_section\n')
        all_etypes = set()
        for mapping_element in mapping.ordered:
            etypes = self._callback('etypes_for', mapping_element)
            all_etypes.update(set(etypes))
100
        all_etypes.remove('SEDAArchiveTransfer')
101
102
        for etype in all_etypes:
            stream.write("ives['{0}'] = 'subobject'\n".format(etype))
103
        # autoform / primary view relation rtags
104
        for rtag, rtag_info in sorted(self.rtags_info.items()):
105
            alias = rtag_info['shortname']
106
107
108
109
110
            stream.write('\n\n{0} = uicfg.{1}\n'.format(rtag_info['shortname'], rtag))
            for mapping_element in mapping.ordered:
                for rtype, role, value in self._callback(rtag + '_for', mapping_element):
                    template = rtag_info[role]
                    stream.write(template.format(**locals()) + '\n')
111
112
113
114
115
116
        # fields order
        stream.write('pvds = uicfg.primaryview_display_ctrl\n')
        for mapping_element in mapping.ordered:
            for etype, attributes in self._callback('order_for', mapping_element):
                stream.write("affk.set_fields_order('{0}', {1})\n".format(etype, attributes))
                stream.write("pvds.set_fields_order('{0}', {1})\n".format(etype, attributes))
117
118

    def etypes_for_e_type_mapping(self, mapping):
119
        yield mapping.etype
120

121
    def autoform_section_for_rdef_mapping(self, mapping):
122
123
124
        if ('afs', mapping.rtype) in self._processed:
            return
        self._processed.add(('afs', mapping.rtype))
125
        if mapping.rtype in RTYPES_IN_TAB:
126
127
128
129
130
131
132
133
            section = 'hidden'
            role = mapping.composite or 'subject'
        elif mapping.composite:
            section = 'inlined'
            role = mapping.composite
        else:
            section = 'attributes'
            role = 'subject'
134
        yield mapping.rtype, neg_role(role), 'hidden'
135
        yield mapping.rtype, role, section
136

137
138
    def autoform_field_kwargs_for_e_type_mapping(self, mapping):
        for rtype, target_etype in sorted(mapping.attributes.items()):
139
140
            if rtype == 'id':
                continue
141
142
            if target_etype == 'String' and ('affk', rtype) not in self._processed:
                self._processed.add(('affk', rtype))
143
                yield rtype, 'subject', {'widget': Code("fw.TextInput({'size': 80})")}
144
145
146
            elif target_etype == 'Boolean' and ('aff', rtype) not in self._processed:
                self._processed.add(('aff', rtype))
                yield rtype, 'subject', {'allow_none': True}
147

148
    def autoform_field_kwargs_for_rdef_mapping(self, mapping):
149
150
        if mapping.rtype.endswith('code_list_version_to'):
            yield mapping.rtype, 'subject', {'label': 'value'}
151
152

    def primaryview_section_for_rdef_mapping(self, mapping):
153
154
155
        if ('pvs', mapping.rtype) in self._processed:
            return
        self._processed.add(('pvs', mapping.rtype))
156
        if mapping.rtype in RTYPES_IN_TAB:
157
158
159
160
            section = 'hidden'
            role = mapping.composite or 'subject'
            yield mapping.rtype, neg_role(role), section
            yield mapping.rtype, role, section
161
162
        elif 'Concept' in mapping.objtypes or 'ConceptScheme' in mapping.objtypes:
            yield mapping.rtype, 'object', 'hidden'
163

164
165
    def reledit_ctrl_for_e_type_mapping(self, mapping):
        for rtype, target_etype in sorted(mapping.attributes.items()):
166
167
            if rtype == 'id':
                continue
168
169
            if ('rec', rtype) not in self._processed:
                self._processed.add(('rec', rtype))
170
                yield rtype, 'subject', _('<no value specified>')
171
172
173
174
175
176

    def reledit_ctrl_for_rdef_mapping(self, mapping):
        if ('rec', mapping.rtype) in self._processed:
            return
        self._processed.add(('rec', mapping.rtype))
        if mapping.composite is None:
177
            yield mapping.rtype, 'subject', '<no value specified>'
178
179
180
        else:
            card = mapping.card[mapping.composite == 'object']
            if card == '1':
181
                yield mapping.rtype, mapping.composite, _('<no value specified>')
182
            elif card == '?':
183
                yield mapping.rtype, mapping.composite, ' '
184

185
186
187
188
189
190
191
192
    def actionbox_appearsin_addmenu_for_rdef_mapping(self, mapping):
        if ('abaa', mapping.rtype) in self._processed:
            return
        self._processed.add(('abaa', mapping.rtype))
        role = mapping.composite or 'subject'
        yield mapping.rtype, neg_role(role), False
        yield mapping.rtype, role, False

193
    def order_for_e_type_mapping(self, mapping):
194
        attributes = ordered_attributes(mapping)
195
196
197
        if len(attributes) > 1:
            yield mapping.etype, attributes

198

199
200
201
class Code(text_type):
    """Special string subclass whose repr() doesn't add quotes, for insertion of python code in a
    data structure
202
203
204
205
206
    """
    def __repr__(self):
        return str(self)


207
208
209
def ordered_attributes(mapping):
    """Given an ETypeMapping, return a list of its attributes sorted by desired order of appearance
    """
210
    attributes = [attr for attr in mapping.attributes if attr != 'id']
211
212
213
    if mapping.etype == 'SEDAArchiveTransfer':
        attributes.append('title')
        attributes.append('user_annotation')
214
215
216
    elif mapping.etype in ('SEDAArchiveUnit', 'SEDABinaryDataObject', 'SEDAPhysicalDataObject'):
        attributes.append('user_cardinality')
        attributes.append('user_annotation')
217
218
    elif attributes:
        if len(mapping.cards) > 1:
219
            attributes.insert(0, 'user_cardinality')
220
221
222
            attributes.append('user_annotation')
    return attributes

223

224
if __name__ == '__main__':
225
    UICFGGenerator.main()