~openerp-dev/openobject-client-web/6.0-opw-598313-msh

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
###############################################################################
#
#  Copyright (C) 2007-TODAY OpenERP SA. All Rights Reserved.
#
#  $Id$
#
#  Developed by OpenERP (http://openerp.com) and Axelor (http://axelor.com).
#
#  The OpenERP web client is distributed under the "OpenERP Public License".
#  It's based on Mozilla Public License Version (MPL) 1.1 with following 
#  restrictions:
#
#  -   All names, links and logos of OpenERP must be kept as in original
#      distribution without any changes in all software screens, especially
#      in start-up page and the software header, even if the application
#      source code has been changed or updated or code has been added.
#
#  You can see the MPL licence at: http://www.mozilla.org/MPL/MPL-1.1.html
#
###############################################################################

import cherrypy

from openobject.widgets import Widget
from openobject.widgets import InputWidget
import simplejson

__all__ = ['TinyWidget', 'TinyInputWidget', 'ConcurrencyInfo',
           'register_widget', 'get_widget', 'get_registered_widgets',
           'InputWidgetLabel']

_attrs_boolean = {
    'select': False,
    'nolabel': False,
    'required': False,
    'readonly': False,
}

def _boolean_attr(attrs, name):

    if name not in _attrs_boolean:
        return attrs.get(name)

    val = attrs.get(name)
    if isinstance(val, basestring) and val.lower() in ('false', 'none', '0'):
        return False

    return (attrs.get(name) and True) or _attrs_boolean.get(name)

class TinyWidget(Widget):

    params = [
        'colspan',
        'rowspan',
        'string',
        'nolabel',
        'visible',
        'valign',
        'model',
        'label'
    ]

    colspan = 1
    rowspan = 1
    string = None
    nolabel = False
    visible = True
    model = None

    valign = "middle"

    def __init__(self, **attrs):

        super(TinyWidget, self).__init__(**attrs)

        prefix = attrs.get('prefix', '')
        self._name = prefix + (prefix and '/' or '') + attrs.get('name', '')

        self.colspan = int(self.colspan)
        self.rowspan = int(self.rowspan)
        self.nolabel = _boolean_attr(attrs, 'nolabel')

        self.visible = True

        try:
            visval = attrs.get('invisible', 'False')
            ctx = attrs.get('context', {})
            self.invisible = eval(visval, {'context': ctx})
        except:
            pass

        self.attributes = attrs.get('attrs', {})

    def get_widgets_by_name(self, name, kind=Widget, parent=None):

        result = []
        parent = parent or self

        for wid in parent.iter_member_widgets():

            if wid.name == name and isinstance(wid, kind):
                result.append(wid)

            if getattr(wid, 'member_widgets', False):
                result += self.get_widgets_by_name(name, kind=kind, parent=wid)

        return result

    @property
    def name(self):
        return self._name

class InputWidgetLabel(Widget):
    template = "/openerp/widgets/templates/label.mako"
    params = ['string', 'help']

    def __init__(self, name, string, help=None):
        super(InputWidgetLabel, self).__init__(name=name, string=string, help=help)

class TinyInputWidget(TinyWidget, InputWidget):
    params = [
        'select',
        'required',
        'readonly',
        'help',
        'editable',
        'translatable',
        'inline',
        'states',
        'callback',
        'change_default',
        'onchange',
        'kind',
        'filters' # filter buttons within an input widget, part of the same implicit "group"
    ]

    select = False
    required = False
    readonly = False
    help = None
    editable = True
    translatable = False
    inline = False

    states = None
    callback = None
    change_default = None
    kind=None

    label_type = InputWidgetLabel

    def __init__(self, **attrs):

        super(TinyInputWidget, self).__init__(**attrs)

        if isinstance(self.states, basestring):
            self.states = self.states.split(',')

        self.select = _boolean_attr(attrs, 'select')
        self.required = _boolean_attr(attrs, 'required')
        self.readonly = _boolean_attr(attrs, 'readonly')

        self.translatable = attrs.get('translate', False)

        self.set_state(attrs.get('state', 'draft'))

        self.callback = attrs.get('on_change', None)
        self.kind = attrs.get('type', None)

        self.label = self.label_type(self.name, self.string, self.help)
        self.filters = []

    def set_state(self, state):
        if isinstance(self.states, dict) and state in self.states:
            attrs = dict(self.states[state])

            self.readonly = attrs.get('readonly', self.readonly)
            self.required = attrs.get('required', self.required)
            self.default = attrs.get('value', self.default)

    def get_value(self):
        """Get the value of the field.

        @return: field value
        """
        return self.default

    def set_value(self, value):
        """Set the value of the field.

        @param value: the value
        """
        if isinstance(value, basestring):
            value = ustr(value)

        self.default = value

    def get_display_value(self):
        """Get the display value of the field.
        """

        try:
            return self.validator.from_python(self.default)
        except:
            pass

        return self.get_value()

    def update_params(self, params):
        super(TinyInputWidget, self).update_params(params)

        params.update(
            kind=self.kind,
            editable=self.editable,
            inline=self.inline,
            attrs={
                'change_default': self.change_default or None,
                'callback': self.callback or None,
                'onchange': self.onchange
            })

        if self.readonly:
            params['attrs']['disabled'] = 'disabled'


class ConcurrencyInfo(TinyInputWidget):
    template = "/openerp/widgets/templates/concurrencyinfo.mako"

    params = ['ids', 'model', 'info']

    def __init__(self, model, ids):
        super(ConcurrencyInfo, self).__init__(model=model, ids=ids)

    @property
    def info(self):
        return getattr(cherrypy.request, 'terp_concurrency_info', {})
    @classmethod
    def update(cls, resource, records):
        info = getattr(cherrypy.request, 'terp_concurrency_info', {})
        vals = info.setdefault(resource, {})
        for item in records:
            vals[item['id']] = item.pop('__last_update', '')
        cherrypy.request.terp_concurrency_info = info
        cherrypy.response.headers['X-Concurrency-Info'] = \
            simplejson.dumps(info)


from openobject import pooler

def register_widget(klass, types, view="form"):
    """Register a widget class for the given view and types

    @param view: the view type (e.g. form, tree)
    @param types: register for the give types
    @param klass: widget class
    """

    if not isinstance(types, (list, tuple)):
        types = [types]

    for t in types:
        pooler.register_object(klass, key=t, group=view)


def get_widget(type, view="form"):
    """Get the widget of the given type for the given view.

    @param view: the view
    @param type: the widget type
    """

    pool = pooler.get_pool()
    return pool.get(type, group=view)


def get_registered_widgets(view="form"):
    """Get all the registered widgets for the given view type.

    @param view: the view
    @returns: dict of all the registered widgets
    """
    pool = pooler.get_pool()
    return pool.get_group(view)


# vim: ts=4 sts=4 sw=4 si et