[ADD] automatic save of o2m rows being created/edited when clicking/focusing outside
[odoo/odoo.git] / addons / web / static / src / js / view_form.js
1 openerp.web.form = function (openerp) {
2
3 var _t = openerp.web._t,
4    _lt = openerp.web._lt;
5 var QWeb = openerp.web.qweb;
6
7 openerp.web.views.add('form', 'openerp.web.FormView');
8 openerp.web.FormView = openerp.web.View.extend( /** @lends openerp.web.FormView# */{
9     /**
10      * Indicates that this view is not searchable, and thus that no search
11      * view should be displayed (if there is one active).
12      */
13     searchable: false,
14     readonly : false,
15     form_template: "FormView",
16     display_name: _lt('Form'),
17     /**
18      * @constructs openerp.web.FormView
19      * @extends openerp.web.View
20      *
21      * @param {openerp.web.Session} session the current openerp session
22      * @param {openerp.web.DataSet} dataset the dataset this view will work with
23      * @param {String} view_id the identifier of the OpenERP view object
24      * @param {Object} options
25      *                  - sidebar : [true|false]
26      *                  - resize_textareas : [true|false|max_height]
27      *
28      * @property {openerp.web.Registry} registry=openerp.web.form.widgets widgets registry for this form view instance
29      */
30     init: function(parent, dataset, view_id, options) {
31         this._super(parent);
32         this.set_default_options(options);
33         this.dataset = dataset;
34         this.model = dataset.model;
35         this.view_id = view_id || false;
36         this.fields_view = {};
37         this.widgets = {};
38         this.widgets_counter = 0;
39         this.fields = {};
40         this.fields_order = [];
41         this.datarecord = {};
42         this.default_focus_field = null;
43         this.default_focus_button = null;
44         this.registry = openerp.web.form.widgets;
45         this.has_been_loaded = $.Deferred();
46         this.$form_header = null;
47         this.translatable_fields = [];
48         _.defaults(this.options, {
49             "not_interactible_on_create": false
50         });
51         this.is_initialized = $.Deferred();
52         this.mutating_mutex = new $.Mutex();
53         this.on_change_mutex = new $.Mutex();
54         this.reload_mutex = new $.Mutex();
55     },
56     start: function() {
57         this._super();
58         return this.init_view();
59     },
60     init_view: function() {
61         if (this.embedded_view) {
62             var def = $.Deferred().then(this.on_loaded);
63             var self = this;
64             $.async_when().then(function() {def.resolve(self.embedded_view);});
65             return def.promise();
66         } else {
67             var context = new openerp.web.CompoundContext(this.dataset.get_context());
68             return this.rpc("/web/view/load", {
69                 "model": this.model,
70                 "view_id": this.view_id,
71                 "view_type": "form",
72                 toolbar: this.options.sidebar,
73                 context: context
74                 }, this.on_loaded);
75         }
76     },
77     stop: function() {
78         if (this.sidebar) {
79             this.sidebar.attachments.stop();
80             this.sidebar.stop();
81         }
82         _.each(this.widgets, function(w) {
83             w.stop();
84         });
85         this._super();
86     },
87     reposition: function ($e) {
88         this.$element = $e;
89         this.on_loaded();
90     },
91     on_loaded: function(data) {
92         var self = this;
93         if (data) {
94             this.fields_order = [];
95             this.fields_view = data;
96             var frame = new (this.registry.get_object('frame'))(this, this.fields_view.arch);
97
98             this.rendered = QWeb.render(this.form_template, { 'frame': frame, 'widget': this });
99         }
100         this.$element.html(this.rendered);
101         _.each(this.widgets, function(w) {
102             w.start();
103         });
104         this.$form_header = this.$element.find('.oe_form_header:first');
105         this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
106             var action = $(this).data('pager-action');
107             self.on_pager_action(action);
108         });
109
110         this.$form_header.find('button.oe_form_button_save').click(this.on_button_save);
111         this.$form_header.find('button.oe_form_button_cancel').click(this.on_button_cancel);
112
113         if (!this.sidebar && this.options.sidebar && this.options.sidebar_id) {
114             this.sidebar = new openerp.web.Sidebar(this, this.options.sidebar_id);
115             this.sidebar.start();
116             this.sidebar.do_unfold();
117             this.sidebar.attachments = new openerp.web.form.SidebarAttachments(this.sidebar, this);
118             this.sidebar.add_toolbar(this.fields_view.toolbar);
119             this.set_common_sidebar_sections(this.sidebar);
120
121             this.sidebar.add_section(_t('Customize'), 'customize');
122             this.sidebar.add_items('customize', [{
123                 label: _t('Set Default'),
124                 form: this,
125                 callback: function (item) {
126                     item.form.open_defaults_dialog();
127                 }
128             }]);
129         }
130         this.has_been_loaded.resolve();
131     },
132
133     do_load_state: function(state, warm) {
134         if (state.id && this.datarecord.id != state.id) {
135             if (!this.dataset.get_id_index(state.id)) {
136                 this.dataset.ids.push(state.id);
137             }
138             this.dataset.select_id(state.id);
139             if (warm) {
140                 this.do_show();
141             }
142         }
143     },
144
145     do_show: function () {
146         var self = this;
147         this.$element.show().css('visibility', 'hidden');
148         this.$element.removeClass('oe_form_dirty');
149         return this.has_been_loaded.pipe(function() {
150             var result;
151             if (self.dataset.index === null) {
152                 // null index means we should start a new record
153                 result = self.on_button_new();
154             } else {
155                 result = self.dataset.read_index(_.keys(self.fields_view.fields), {
156                     context : { 'bin_size' : true }
157                 }).pipe(self.on_record_loaded);
158             }
159             result.pipe(function() {
160                 self.$element.css('visibility', 'visible');
161             });
162             if (self.sidebar) {
163                 self.sidebar.$element.show();
164             }
165             return result;
166         });
167     },
168     do_hide: function () {
169         this._super();
170         if (this.sidebar) {
171             this.sidebar.$element.hide();
172         }
173     },
174     on_record_loaded: function(record) {
175         var self = this, set_values = [];
176         if (!record) {
177             this.do_warn("Form", "The record could not be found in the database.", true);
178             return $.Deferred().reject();
179         }
180         this.datarecord = record;
181
182         _(this.fields).each(function (field, f) {
183             field.reset();
184             var result = field.set_value(self.datarecord[f] || false);
185             set_values.push(result);
186             $.when(result).then(function() {
187                 field.validate();
188             });
189         });
190         return $.when.apply(null, set_values).pipe(function() {
191             if (!record.id) {
192                 // New record: Second pass in order to trigger the onchanges
193                 // respecting the fields order defined in the view
194                 _.each(self.fields_order, function(field_name) {
195                     if (record[field_name] !== undefined) {
196                         var field = self.fields[field_name];
197                         field.dirty = true;
198                         self.do_onchange(field);
199                     }
200                 });
201             }
202             self.on_form_changed();
203             self.is_initialized.resolve();
204             self.do_update_pager(record.id == null);
205             if (self.sidebar) {
206                 self.sidebar.attachments.do_update();
207             }
208             if (self.default_focus_field) {
209                 self.default_focus_field.focus();
210             }
211             if (record.id) {
212                 self.do_push_state({id:record.id});
213             }
214             self.$element.removeClass('oe_form_dirty');
215         });
216     },
217     on_form_changed: function() {
218         for (var w in this.widgets) {
219             w = this.widgets[w];
220             w.process_modifiers();
221             if (w.field) {
222                 w.validate();
223             }
224             w.update_dom();
225         }
226     },
227     do_notify_change: function() {
228         this.$element.addClass('oe_form_dirty');
229     },
230     on_pager_action: function(action) {
231         if (this.can_be_discarded()) {
232             switch (action) {
233                 case 'first':
234                     this.dataset.index = 0;
235                     break;
236                 case 'previous':
237                     this.dataset.previous();
238                     break;
239                 case 'next':
240                     this.dataset.next();
241                     break;
242                 case 'last':
243                     this.dataset.index = this.dataset.ids.length - 1;
244                     break;
245             }
246             this.reload();
247         }
248     },
249     do_update_pager: function(hide_index) {
250         var $pager = this.$form_header.find('div.oe_form_pager');
251         var index = hide_index ? '-' : this.dataset.index + 1;
252         $pager.find('button').prop('disabled', this.dataset.ids.length < 2);
253         $pager.find('span.oe_pager_index').html(index);
254         $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
255     },
256     parse_on_change: function (on_change, widget) {
257         var self = this;
258         var onchange = _.str.trim(on_change);
259         var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
260         if (!call) {
261             return null;
262         }
263
264         var method = call[1];
265         if (!_.str.trim(call[2])) {
266             return {method: method, args: [], context_index: null}
267         }
268
269         var argument_replacement = {
270             'False': function () {return false;},
271             'True': function () {return true;},
272             'None': function () {return null;},
273             'context': function (i) {
274                 context_index = i;
275                 var ctx = new openerp.web.CompoundContext(self.dataset.get_context(), widget.build_context() ? widget.build_context() : {});
276                 return ctx;
277             }
278         };
279         var parent_fields = null, context_index = null;
280         var args = _.map(call[2].split(','), function (a, i) {
281             var field = _.str.trim(a);
282
283             // literal constant or context
284             if (field in argument_replacement) {
285                 return argument_replacement[field](i);
286             }
287             // literal number
288             if (/^-?\d+(\.\d+)?$/.test(field)) {
289                 return Number(field);
290             }
291             // form field
292             if (self.fields[field]) {
293                 var value = self.fields[field].get_on_change_value();
294                 return value == null ? false : value;
295             }
296             // parent field
297             var splitted = field.split('.');
298             if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
299                 if (parent_fields === null) {
300                     parent_fields = self.dataset.parent_view.get_fields_values([self.dataset.child_name]);
301                 }
302                 var p_val = parent_fields[_.str.trim(splitted[1])];
303                 if (p_val !== undefined) {
304                     return p_val == null ? false : p_val;
305                 }
306             }
307             // string literal
308             var first_char = field[0], last_char = field[field.length-1];
309             if ((first_char === '"' && last_char === '"')
310                 || (first_char === "'" && last_char === "'")) {
311                 return field.slice(1, -1);
312             }
313
314             throw new Error("Could not get field with name '" + field +
315                             "' for onchange '" + onchange + "'");
316         });
317
318         return {
319             method: method,
320             args: args,
321             context_index: context_index
322         };
323     },
324     do_onchange: function(widget, processed) {
325         var self = this;
326         return this.on_change_mutex.exec(function() {
327             try {
328                 var response = {}, can_process_onchange = $.Deferred();
329                 processed = processed || [];
330                 processed.push(widget.name);
331                 var on_change = widget.node.attrs.on_change;
332                 if (on_change) {
333                     var change_spec = self.parse_on_change(on_change, widget);
334                     if (change_spec) {
335                         var ajax = {
336                             url: '/web/dataset/onchange',
337                             async: false
338                         };
339                         can_process_onchange = self.rpc(ajax, {
340                             model: self.dataset.model,
341                             method: change_spec.method,
342                             args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
343                             context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
344                         }).then(function(r) {
345                             _.extend(response, r);
346                         });
347                     } else {
348                         console.warn("Wrong on_change format", on_change);
349                     }
350                 }
351                 // fail if onchange failed
352                 if (can_process_onchange.isRejected()) {
353                     return can_process_onchange;
354                 }
355
356                 if (widget.field['change_default']) {
357                     var fieldname = widget.name, value;
358                     if (response.value && (fieldname in response.value)) {
359                         // Use value from onchange if onchange executed
360                         value = response.value[fieldname];
361                     } else {
362                         // otherwise get form value for field
363                         value = self.fields[fieldname].get_on_change_value();
364                     }
365                     var condition = fieldname + '=' + value;
366
367                     if (value) {
368                         can_process_onchange = self.rpc({
369                             url: '/web/dataset/call',
370                             async: false
371                         }, {
372                             model: 'ir.values',
373                             method: 'get_defaults',
374                             args: [self.model, condition]
375                         }).then(function (results) {
376                             if (!results.length) { return; }
377                             if (!response.value) {
378                                 response.value = {};
379                             }
380                             for(var i=0; i<results.length; ++i) {
381                                 // [whatever, key, value]
382                                 var triplet = results[i];
383                                 response.value[triplet[1]] = triplet[2];
384                             }
385                         });
386                     }
387                 }
388                 if (can_process_onchange.isRejected()) {
389                     return can_process_onchange;
390                 }
391
392                 return self.on_processed_onchange(response, processed);
393             } catch(e) {
394                 console.error(e);
395                 return $.Deferred().reject();
396             }
397         });
398     },
399     on_processed_onchange: function(response, processed) {
400         try {
401         var result = response;
402         if (result.value) {
403             for (var f in result.value) {
404                 if (!result.value.hasOwnProperty(f)) { continue; }
405                 var field = this.fields[f];
406                 // If field is not defined in the view, just ignore it
407                 if (field) {
408                     var value = result.value[f];
409                     if (field.get_value() != value) {
410                         field.set_value(value);
411                         field.dirty = true;
412                         if (!_.contains(processed, field.name)) {
413                             this.do_onchange(field, processed);
414                         }
415                     }
416                 }
417             }
418             this.on_form_changed();
419         }
420         if (!_.isEmpty(result.warning)) {
421             $(QWeb.render("CrashManagerWarning", result.warning)).dialog({
422                 modal: true,
423                 buttons: [
424                     {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
425                 ]
426             });
427         }
428         if (result.domain) {
429             function edit_domain(node) {
430                 var new_domain = result.domain[node.attrs.name];
431                 if (new_domain) {
432                     node.attrs.domain = new_domain;
433                 }
434                 _(node.children).each(edit_domain);
435             }
436             edit_domain(this.fields_view.arch);
437         }
438         return $.Deferred().resolve();
439         } catch(e) {
440             console.error(e);
441             return $.Deferred().reject();
442         }
443     },
444     on_button_save: function() {
445         var self = this;
446         return this.do_save().then(function(result) {
447             self.do_prev_view({'created': result.created, 'default': 'page'});
448         });
449     },
450     on_button_cancel: function() {
451         if (this.can_be_discarded()) {
452             return this.do_prev_view({'default': 'page'});
453         }
454     },
455     on_button_new: function() {
456         var self = this;
457         var def = $.Deferred();
458         $.when(this.has_been_loaded).then(function() {
459             if (self.can_be_discarded()) {
460                 var keys = _.keys(self.fields_view.fields);
461                 if (keys.length) {
462                     self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
463                         def.resolve();
464                     });
465                 } else {
466                     self.on_record_loaded({}).then(function() {
467                         def.resolve();
468                     });
469                 }
470             }
471         });
472         return def.promise();
473     },
474     can_be_discarded: function() {
475         return !this.$element.is('.oe_form_dirty') || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
476     },
477     /**
478      * Triggers saving the form's record. Chooses between creating a new
479      * record or saving an existing one depending on whether the record
480      * already has an id property.
481      *
482      * @param {Function} success callback on save success
483      * @param {Boolean} [prepend_on_create=false] if ``do_save`` creates a new record, should that record be inserted at the start of the dataset (by default, records are added at the end)
484      */
485     do_save: function(success, prepend_on_create) {
486         var self = this;
487         return this.mutating_mutex.exec(function() { return self.is_initialized.pipe(function() {
488             try {
489             var form_invalid = false,
490                 values = {},
491                 first_invalid_field = null;
492             for (var f in self.fields) {
493                 f = self.fields[f];
494                 if (!f.is_valid()) {
495                     form_invalid = true;
496                     f.update_dom(true);
497                     if (!first_invalid_field) {
498                         first_invalid_field = f;
499                     }
500                 } else if (f.name !== 'id' && !f.readonly && (!self.datarecord.id || f.is_dirty())) {
501                     // Special case 'id' field, do not save this field
502                     // on 'create' : save all non readonly fields
503                     // on 'edit' : save non readonly modified fields
504                     values[f.name] = f.get_value();
505                 }
506             }
507             if (form_invalid) {
508                 first_invalid_field.focus();
509                 self.on_invalid();
510                 return $.Deferred().reject();
511             } else {
512                 var save_deferral;
513                 if (!self.datarecord.id) {
514                     //console.log("FormView(", self, ") : About to create", values);
515                     save_deferral = self.dataset.create(values).pipe(function(r) {
516                         return self.on_created(r, undefined, prepend_on_create);
517                     }, null);
518                 } else if (_.isEmpty(values) && ! self.force_dirty) {
519                     //console.log("FormView(", self, ") : Nothing to save");
520                     save_deferral = $.Deferred().resolve({}).promise();
521                 } else {
522                     self.force_dirty = false;
523                     //console.log("FormView(", self, ") : About to save", values);
524                     save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
525                         return self.on_saved(r);
526                     }, null);
527                 }
528                 return save_deferral.then(success);
529             }
530             } catch (e) {
531                 console.error(e);
532                 return $.Deferred().reject();
533             }
534         });});
535     },
536     on_invalid: function() {
537         var msg = "<ul>";
538         _.each(this.fields, function(f) {
539             if (!f.is_valid()) {
540                 msg += "<li>" + f.string + "</li>";
541             }
542         });
543         msg += "</ul>";
544         this.do_warn("The following fields are invalid :", msg);
545     },
546     on_saved: function(r, success) {
547         if (!r.result) {
548             // should not happen in the server, but may happen for internal purpose
549             return $.Deferred().reject();
550         } else {
551             return $.when(this.reload()).pipe(function () {
552                 return r; })
553                     .then(success);
554         }
555     },
556     /**
557      * Updates the form' dataset to contain the new record:
558      *
559      * * Adds the newly created record to the current dataset (at the end by
560      *   default)
561      * * Selects that record (sets the dataset's index to point to the new
562      *   record's id).
563      * * Updates the pager and sidebar displays
564      *
565      * @param {Object} r
566      * @param {Function} success callback to execute after having updated the dataset
567      * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
568      */
569     on_created: function(r, success, prepend_on_create) {
570         if (!r.result) {
571             // should not happen in the server, but may happen for internal purpose
572             return $.Deferred().reject();
573         } else {
574             this.datarecord.id = r.result;
575             if (!prepend_on_create) {
576                 this.dataset.alter_ids(this.dataset.ids.concat([this.datarecord.id]));
577                 this.dataset.index = this.dataset.ids.length - 1;
578             } else {
579                 this.dataset.alter_ids([this.datarecord.id].concat(this.dataset.ids));
580                 this.dataset.index = 0;
581             }
582             this.do_update_pager();
583             if (this.sidebar) {
584                 this.sidebar.attachments.do_update();
585             }
586             //openerp.log("The record has been created with id #" + this.datarecord.id);
587             return $.when(this.reload()).pipe(function () {
588                 return _.extend(r, {created: true}); })
589                     .then(success);
590         }
591     },
592     on_action: function (action) {
593         console.debug('Executing action', action);
594     },
595     reload: function() {
596         var self = this;
597         return this.reload_mutex.exec(function() {
598             if (self.dataset.index == null || self.dataset.index < 0) {
599                 return $.when(self.on_button_new());
600             } else {
601                 return self.dataset.read_index(_.keys(self.fields_view.fields), {
602                     context : { 'bin_size' : true }
603                 }).pipe(self.on_record_loaded);
604             }
605         });
606     },
607     get_fields_values: function(blacklist) {
608         blacklist = blacklist || [];
609         var values = {};
610         var ids = this.get_selected_ids();
611         values["id"] = ids.length > 0 ? ids[0] : false;
612         _.each(this.fields, function(value, key) {
613                 if (_.include(blacklist, key))
614                         return;
615             var val = value.get_value();
616             values[key] = val;
617         });
618         return values;
619     },
620     get_selected_ids: function() {
621         var id = this.dataset.ids[this.dataset.index];
622         return id ? [id] : [];
623     },
624     recursive_save: function() {
625         var self = this;
626         return $.when(this.do_save()).pipe(function(res) {
627             if (self.dataset.parent_view)
628                 return self.dataset.parent_view.recursive_save();
629         });
630     },
631     is_dirty: function() {
632         return _.any(this.fields, function (value) {
633             return value.is_dirty();
634         });
635     },
636     is_interactible_record: function() {
637         var id = this.datarecord.id;
638         if (!id) {
639             if (this.options.not_interactible_on_create)
640                 return false;
641         } else if (typeof(id) === "string") {
642             if(openerp.web.BufferedDataSet.virtual_id_regex.test(id))
643                 return false;
644         }
645         return true;
646     },
647     sidebar_context: function () {
648         return this.do_save().pipe(_.bind(function() {return this.get_fields_values();}, this));
649     },
650     open_defaults_dialog: function () {
651         var self = this;
652         var fields = _.chain(this.fields)
653             .map(function (field, name) {
654                 var value = field.get_value();
655                 // ignore fields which are empty, invisible, readonly, o2m
656                 // or m2m
657                 if (!value
658                         || field.invisible
659                         || field.readonly
660                         || field.field.type === 'one2many'
661                         || field.field.type === 'many2many') {
662                     return false;
663                 }
664                 var displayed;
665                 switch(field.field.type) {
666                 case 'selection':
667                     displayed = _(field.values).find(function (option) {
668                             return option[0] === value;
669                         })[1];
670                     break;
671                 case 'many2one':
672                     displayed = field.value[1] || value;
673                     break;
674                 default:
675                     displayed = value;
676                 }
677
678                 return {
679                     name: name,
680                     string: field.string,
681                     value: value,
682                     displayed: displayed,
683                     // convert undefined to false
684                     change_default: !!field.field.change_default
685                 }
686             })
687             .compact()
688             .sortBy(function (field) { return field.string; })
689             .value();
690         var conditions = _.chain(fields)
691             .filter(function (field) { return field.change_default; })
692             .value();
693
694         var d = new openerp.web.Dialog(this, {
695             title: _t("Set Default"),
696             args: {
697                 fields: fields,
698                 conditions: conditions
699             },
700             buttons: [
701                 {text: _t("Close"), click: function () { d.close(); }},
702                 {text: _t("Save default"), click: function () {
703                     var $defaults = d.$element.find('#formview_default_fields');
704                     var field_to_set = $defaults.val();
705                     if (!field_to_set) {
706                         $defaults.parent().addClass('invalid');
707                         return;
708                     }
709                     var condition = d.$element.find('#formview_default_conditions').val(),
710                         all_users = d.$element.find('#formview_default_all').is(':checked');
711                     new openerp.web.DataSet(self, 'ir.values').call(
712                         'set_default', [
713                             self.dataset.model,
714                             field_to_set,
715                             self.fields[field_to_set].get_value(),
716                             all_users,
717                             false,
718                             condition || false
719                     ]).then(function () { d.close(); });
720                 }}
721             ]
722         });
723         d.template = 'FormView.set_default';
724         d.open();
725     }
726 });
727 openerp.web.FormDialog = openerp.web.Dialog.extend({
728     init: function(parent, options, view_id, dataset) {
729         this._super(parent, options);
730         this.dataset = dataset;
731         this.view_id = view_id;
732         return this;
733     },
734     start: function() {
735         this._super();
736         this.form = new openerp.web.FormView(this, this.dataset, this.view_id, {
737             sidebar: false,
738             pager: false
739         });
740         this.form.appendTo(this.$element);
741         this.form.on_created.add_last(this.on_form_dialog_saved);
742         this.form.on_saved.add_last(this.on_form_dialog_saved);
743         return this;
744     },
745     select_id: function(id) {
746         if (this.form.dataset.select_id(id)) {
747             return this.form.do_show();
748         } else {
749             this.do_warn("Could not find id in dataset");
750             return $.Deferred().reject();
751         }
752     },
753     on_form_dialog_saved: function(r) {
754         this.close();
755     }
756 });
757
758 /** @namespace */
759 openerp.web.form = {};
760
761 openerp.web.form.SidebarAttachments = openerp.web.OldWidget.extend({
762     init: function(parent, form_view) {
763         var $section = parent.add_section(_t('Attachments'), 'attachments');
764         this.$div = $('<div class="oe-sidebar-attachments"></div>');
765         $section.append(this.$div);
766
767         this._super(parent, $section.attr('id'));
768         this.view = form_view;
769     },
770     do_update: function() {
771         if (!this.view.datarecord.id) {
772             this.on_attachments_loaded([]);
773         } else {
774             (new openerp.web.DataSetSearch(
775                 this, 'ir.attachment', this.view.dataset.get_context(),
776                 [
777                     ['res_model', '=', this.view.dataset.model],
778                     ['res_id', '=', this.view.datarecord.id],
779                     ['type', 'in', ['binary', 'url']]
780                 ])).read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
781         }
782     },
783     on_attachments_loaded: function(attachments) {
784         this.attachments = attachments;
785         this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
786         this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
787         this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
788     },
789     on_attachment_changed: function(e) {
790         window[this.element_id + '_iframe'] = this.do_update;
791         var $e = $(e.target);
792         if ($e.val() != '') {
793             this.$element.find('form.oe-binary-form').submit();
794             $e.parent().find('input[type=file]').prop('disabled', true);
795             $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
796         }
797     },
798     on_attachment_delete: function(e) {
799         var self = this, $e = $(e.currentTarget);
800         var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
801         if (confirm(_.str.sprintf(_t("Do you really want to delete the attachment %s?"), name))) {
802             this.rpc('/web/dataset/unlink', {
803                 model: 'ir.attachment',
804                 ids: [parseInt($e.attr('data-id'))]
805             }, function(r) {
806                 $e.parent().remove();
807                 self.do_update()
808                 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
809             });
810         }
811     }
812 });
813
814 openerp.web.form.compute_domain = function(expr, fields) {
815     var stack = [];
816     for (var i = expr.length - 1; i >= 0; i--) {
817         var ex = expr[i];
818         if (ex.length == 1) {
819             var top = stack.pop();
820             switch (ex) {
821                 case '|':
822                     stack.push(stack.pop() || top);
823                     continue;
824                 case '&':
825                     stack.push(stack.pop() && top);
826                     continue;
827                 case '!':
828                     stack.push(!top);
829                     continue;
830                 default:
831                     throw new Error(_.str.sprintf(
832                         _t("Unknown operator %s in domain %s"),
833                         ex, JSON.stringify(expr)));
834             }
835         }
836
837         var field = fields[ex[0]];
838         if (!field) {
839             throw new Error(_.str.sprintf(
840                 _t("Unknown field %s in domain %s"),
841                 ex[0], JSON.stringify(expr)));
842         }
843         var field_value = field.get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
844         var op = ex[1];
845         var val = ex[2];
846
847         switch (op.toLowerCase()) {
848             case '=':
849             case '==':
850                 stack.push(field_value == val);
851                 break;
852             case '!=':
853             case '<>':
854                 stack.push(field_value != val);
855                 break;
856             case '<':
857                 stack.push(field_value < val);
858                 break;
859             case '>':
860                 stack.push(field_value > val);
861                 break;
862             case '<=':
863                 stack.push(field_value <= val);
864                 break;
865             case '>=':
866                 stack.push(field_value >= val);
867                 break;
868             case 'in':
869                 if (!_.isArray(val)) val = [val];
870                 stack.push(_(val).contains(field_value));
871                 break;
872             case 'not in':
873                 if (!_.isArray(val)) val = [val];
874                 stack.push(!_(val).contains(field_value));
875                 break;
876             default:
877                 console.warn(
878                     _t("Unsupported operator %s in domain %s"),
879                     op, JSON.stringify(expr));
880         }
881     }
882     return _.all(stack, _.identity);
883 };
884
885 openerp.web.form.Widget = openerp.web.OldWidget.extend(/** @lends openerp.web.form.Widget# */{
886     template: 'Widget',
887     /**
888      * @constructs openerp.web.form.Widget
889      * @extends openerp.web.OldWidget
890      *
891      * @param view
892      * @param node
893      */
894     init: function(view, node) {
895         this.view = view;
896         this.node = node;
897         this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
898         this.always_invisible = (this.modifiers.invisible && this.modifiers.invisible === true);
899         this.type = this.type || node.tag;
900         this.element_name = this.element_name || this.type;
901         this.element_class = [
902             'formview', this.view.view_id, this.element_name,
903             this.view.widgets_counter++].join("_");
904
905         this._super(view);
906
907         this.view.widgets[this.element_class] = this;
908         this.children = node.children;
909         this.colspan = parseInt(node.attrs.colspan || 1, 10);
910         this.decrease_max_width = 0;
911
912         this.string = this.string || node.attrs.string;
913         this.help = this.help || node.attrs.help;
914         this.invisible = this.modifiers['invisible'] === true;
915         this.classname = 'oe_form_' + this.type;
916
917         this.align = parseFloat(this.node.attrs.align);
918         if (isNaN(this.align) || this.align === 1) {
919             this.align = 'right';
920         } else if (this.align === 0) {
921             this.align = 'left';
922         } else {
923             this.align = 'center';
924         }
925
926
927         this.width = this.node.attrs.width;
928     },
929     start: function() {
930         this.$element = this.view.$element.find(
931             '.' + this.element_class.replace(/[^\r\n\f0-9A-Za-z_-]/g, "\\$&"));
932     },
933     stop: function() {
934         this._super.apply(this, arguments);
935         $.fn.tipsy.clear();
936     },
937     process_modifiers: function() {
938         var compute_domain = openerp.web.form.compute_domain;
939         for (var a in this.modifiers) {
940             this[a] = compute_domain(this.modifiers[a], this.view.fields);
941         }
942     },
943     update_dom: function() {
944         this.$element.toggle(!this.invisible);
945     },
946     render: function() {
947         var template = this.template;
948         return QWeb.render(template, { "widget": this });
949     },
950     do_attach_tooltip: function(widget, trigger, options) {
951         widget = widget || this;
952         trigger = trigger || this.$element;
953         options = _.extend({
954                 delayIn: 500,
955                 delayOut: 0,
956                 fade: true,
957                 title: function() {
958                     var template = widget.template + '.tooltip';
959                     if (!QWeb.has_template(template)) {
960                         template = 'WidgetLabel.tooltip';
961                     }
962                     return QWeb.render(template, {
963                         debug: openerp.connection.debug,
964                         widget: widget
965                 })},
966                 gravity: $.fn.tipsy.autoBounds(50, 'nw'),
967                 html: true,
968                 opacity: 0.85,
969                 trigger: 'hover'
970             }, options || {});
971         trigger.tipsy(options);
972     },
973     _build_view_fields_values: function(blacklist) {
974         var a_dataset = this.view.dataset;
975         var fields_values = this.view.get_fields_values(blacklist);
976         var active_id = a_dataset.ids[a_dataset.index];
977         _.extend(fields_values, {
978             active_id: active_id || false,
979             active_ids: active_id ? [active_id] : [],
980             active_model: a_dataset.model,
981             parent: {}
982         });
983         if (a_dataset.parent_view) {
984                 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
985         }
986         return fields_values;
987     },
988     _build_eval_context: function(blacklist) {
989         var a_dataset = this.view.dataset;
990         return new openerp.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
991     },
992     /**
993      * Builds a new context usable for operations related to fields by merging
994      * the fields'context with the action's context.
995      */
996     build_context: function(blacklist) {
997         // only use the model's context if there is not context on the node
998         var v_context = this.node.attrs.context;
999         if (! v_context) {
1000             v_context = (this.field || {}).context || {};
1001         }
1002         
1003         if (v_context.__ref || true) { //TODO: remove true
1004             var fields_values = this._build_eval_context(blacklist);
1005             v_context = new openerp.web.CompoundContext(v_context).set_eval_context(fields_values);
1006         }
1007         return v_context;
1008     },
1009     build_domain: function() {
1010         var f_domain = this.field.domain || [];
1011         var n_domain = this.node.attrs.domain || null;
1012         // if there is a domain on the node, overrides the model's domain
1013         var final_domain = n_domain !== null ? n_domain : f_domain;
1014         if (!(final_domain instanceof Array) || true) { //TODO: remove true
1015             var fields_values = this._build_eval_context();
1016             final_domain = new openerp.web.CompoundDomain(final_domain).set_eval_context(fields_values);
1017         }
1018         return final_domain;
1019     }
1020 });
1021
1022 openerp.web.form.WidgetFrame = openerp.web.form.Widget.extend({
1023     template: 'WidgetFrame',
1024     init: function(view, node) {
1025         this._super(view, node);
1026         this.columns = parseInt(node.attrs.col || 4, 10);
1027         this.x = 0;
1028         this.y = 0;
1029         this.table = [];
1030         this.add_row();
1031         for (var i = 0; i < node.children.length; i++) {
1032             var n = node.children[i];
1033             if (n.tag == "newline") {
1034                 this.add_row();
1035             } else {
1036                 this.handle_node(n);
1037             }
1038         }
1039         this.set_row_cells_with(this.table[this.table.length - 1]);
1040     },
1041     add_row: function(){
1042         if (this.table.length) {
1043             this.set_row_cells_with(this.table[this.table.length - 1]);
1044         }
1045         var row = [];
1046         this.table.push(row);
1047         this.x = 0;
1048         this.y += 1;
1049         return row;
1050     },
1051     set_row_cells_with: function(row) {
1052         var bypass = 0,
1053             max_width = 100,
1054             row_length = row.length;
1055         for (var i = 0; i < row.length; i++) {
1056             if (row[i].always_invisible) {
1057                 row_length--;
1058             } else {
1059                 bypass += row[i].width === undefined ? 0 : 1;
1060                 max_width -= row[i].decrease_max_width;
1061             }
1062         }
1063         var size_unit = Math.round(max_width / (this.columns - bypass)),
1064             colspan_sum = 0;
1065         for (var i = 0; i < row.length; i++) {
1066             var w = row[i];
1067             if (w.always_invisible) {
1068                 continue;
1069             }
1070             colspan_sum += w.colspan;
1071             if (w.width === undefined) {
1072                 var width = (i === row_length - 1 && colspan_sum === this.columns) ? max_width : Math.round(size_unit * w.colspan);
1073                 max_width -= width;
1074                 w.width = width + '%';
1075             }
1076         }
1077     },
1078     handle_node: function(node) {
1079         var type = {};
1080         if (node.tag == 'field') {
1081             type = this.view.fields_view.fields[node.attrs.name] || {};
1082             if (node.attrs.widget == 'statusbar' && node.attrs.nolabel !== '1') {
1083                 // This way we can retain backward compatibility between addons and old clients
1084                 node.attrs.colspan = (parseInt(node.attrs.colspan, 10) || 1) + 1;
1085                 node.attrs.nolabel = '1';
1086             }
1087         }
1088         var widget = new (this.view.registry.get_any(
1089                 [node.attrs.widget, type.type, node.tag])) (this.view, node);
1090         if (node.tag == 'field') {
1091             if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
1092                 this.view.default_focus_field = widget;
1093             }
1094             if (node.attrs.nolabel != '1') {
1095                 var label = new (this.view.registry.get_object('label')) (this.view, node);
1096                 label["for"] = widget;
1097                 this.add_widget(label, widget.colspan + 1);
1098             }
1099         }
1100         this.add_widget(widget);
1101     },
1102     add_widget: function(widget, colspan) {
1103         var current_row = this.table[this.table.length - 1];
1104         if (!widget.always_invisible) {
1105             colspan = colspan || widget.colspan;
1106             if (current_row.length && (this.x + colspan) > this.columns) {
1107                 current_row = this.add_row();
1108             }
1109             this.x += widget.colspan;
1110         }
1111         current_row.push(widget);
1112         return widget;
1113     }
1114 });
1115
1116 openerp.web.form.WidgetGroup = openerp.web.form.WidgetFrame.extend({
1117     template: 'WidgetGroup'
1118 }),
1119
1120 openerp.web.form.WidgetNotebook = openerp.web.form.Widget.extend({
1121     template: 'WidgetNotebook',
1122     init: function(view, node) {
1123         this._super(view, node);
1124         this.pages = [];
1125         for (var i = 0; i < node.children.length; i++) {
1126             var n = node.children[i];
1127             if (n.tag == "page") {
1128                 var page = new (this.view.registry.get_object('notebookpage'))(
1129                         this.view, n, this, this.pages.length);
1130                 this.pages.push(page);
1131             }
1132         }
1133     },
1134     start: function() {
1135         var self = this;
1136         this._super.apply(this, arguments);
1137         this.$element.find('> ul > li').each(function (index, tab_li) {
1138             var page = self.pages[index],
1139                 id = _.uniqueId(self.element_name + '-');
1140             page.element_id = id;
1141             $(tab_li).find('a').attr('href', '#' + id);
1142         });
1143         this.$element.find('> div').each(function (index, page) {
1144             page.id = self.pages[index].element_id;
1145         });
1146         this.$element.tabs();
1147         this.view.on_button_new.add_first(this.do_select_first_visible_tab);
1148         if (openerp.connection.debug) {
1149             this.do_attach_tooltip(this, this.$element.find('ul:first'), {
1150                 gravity: 's'
1151             });
1152         }
1153     },
1154     do_select_first_visible_tab: function() {
1155         for (var i = 0; i < this.pages.length; i++) {
1156             var page = this.pages[i];
1157             if (page.invisible === false) {
1158                 this.$element.tabs('select', page.index);
1159                 break;
1160             }
1161         }
1162     }
1163 });
1164
1165 openerp.web.form.WidgetNotebookPage = openerp.web.form.WidgetFrame.extend({
1166     template: 'WidgetNotebookPage',
1167     init: function(view, node, notebook, index) {
1168         this.notebook = notebook;
1169         this.index = index;
1170         this.element_name = 'page_' + index;
1171         this._super(view, node);
1172     },
1173     start: function() {
1174         this._super.apply(this, arguments);
1175         this.$element_tab = this.notebook.$element.find(
1176                 '> ul > li:eq(' + this.index + ')');
1177     },
1178     update_dom: function() {
1179         if (this.invisible && this.index === this.notebook.$element.tabs('option', 'selected')) {
1180             this.notebook.do_select_first_visible_tab();
1181         }
1182         this.$element_tab.toggle(!this.invisible);
1183         this.$element.toggle(!this.invisible);
1184     }
1185 });
1186
1187 openerp.web.form.WidgetSeparator = openerp.web.form.Widget.extend({
1188     template: 'WidgetSeparator',
1189     init: function(view, node) {
1190         this._super(view, node);
1191         this.orientation = node.attrs.orientation || 'horizontal';
1192         if (this.orientation === 'vertical') {
1193             this.width = '1';
1194         }
1195         this.classname += '_' + this.orientation;
1196     }
1197 });
1198
1199 openerp.web.form.WidgetButton = openerp.web.form.Widget.extend({
1200     template: 'WidgetButton',
1201     init: function(view, node) {
1202         this._super(view, node);
1203         this.force_disabled = false;
1204         if (this.string) {
1205             // We don't have button key bindings in the webclient
1206             this.string = this.string.replace(/_/g, '');
1207         }
1208         if (node.attrs.default_focus == '1') {
1209             // TODO fme: provide enter key binding to widgets
1210             this.view.default_focus_button = this;
1211         }
1212     },
1213     start: function() {
1214         this._super.apply(this, arguments);
1215         this.$element.find("button").click(this.on_click);
1216         if (this.help || openerp.connection.debug) {
1217             this.do_attach_tooltip();
1218         }
1219     },
1220     on_click: function() {
1221         var self = this;
1222         this.force_disabled = true;
1223         this.check_disable();
1224         this.execute_action().always(function() {
1225             self.force_disabled = false;
1226             self.check_disable();
1227         });
1228     },
1229     execute_action: function() {
1230         var self = this;
1231         var exec_action = function() {
1232             if (self.node.attrs.confirm) {
1233                 var def = $.Deferred();
1234                 var dialog = $('<div>' + self.node.attrs.confirm + '</div>').dialog({
1235                     title: _t('Confirm'),
1236                     modal: true,
1237                     buttons: [
1238                         {text: _t("Cancel"), click: function() {
1239                                 def.resolve();
1240                                 $(this).dialog("close");
1241                             }
1242                         },
1243                         {text: _t("Ok"), click: function() {
1244                                 self.on_confirmed().then(function() {
1245                                     def.resolve();
1246                                 });
1247                                 $(this).dialog("close");
1248                             }
1249                         }
1250                     ]
1251                 });
1252                 return def.promise();
1253             } else {
1254                 return self.on_confirmed();
1255             }
1256         };
1257         if (!this.node.attrs.special) {
1258             this.view.force_dirty = true;
1259             return this.view.recursive_save().pipe(exec_action);
1260         } else {
1261             return exec_action();
1262         }
1263     },
1264     on_confirmed: function() {
1265         var self = this;
1266
1267         var context = this.node.attrs.context;
1268         if (context && context.__ref) {
1269             context = new openerp.web.CompoundContext(context);
1270             context.set_eval_context(this._build_eval_context());
1271         }
1272
1273         return this.view.do_execute_action(
1274             _.extend({}, this.node.attrs, {context: context}),
1275             this.view.dataset, this.view.datarecord.id, function () {
1276                 self.view.reload();
1277             });
1278     },
1279     update_dom: function() {
1280         this._super.apply(this, arguments);
1281         this.check_disable();
1282     },
1283     check_disable: function() {
1284         var disabled = (this.readonly || this.force_disabled || !this.view.is_interactible_record());
1285         this.$element.find('button').prop('disabled', disabled);
1286         this.$element.find("button").css('color', disabled ? 'grey' : '');
1287     }
1288 });
1289
1290 openerp.web.form.WidgetLabel = openerp.web.form.Widget.extend({
1291     template: 'WidgetLabel',
1292     init: function(view, node) {
1293         this.element_name = 'label_' + node.attrs.name;
1294
1295         this._super(view, node);
1296
1297         if (this.node.tag == 'label' && !this.string && this.node.children.length) {
1298             this.string = this.node.children[0];
1299             this.align = 'left';
1300         }
1301
1302         if (this.node.tag == 'label' && (this.align === 'left' || this.node.attrs.colspan || (this.string && this.string.length > 32))) {
1303             this.template = "WidgetParagraph";
1304             this.colspan = parseInt(this.node.attrs.colspan || 1, 10);
1305             // Widgets default to right-aligned, but paragraph defaults to
1306             // left-aligned
1307             if (isNaN(parseFloat(this.node.attrs.align))) {
1308                 this.align = 'left';
1309             }
1310
1311             this.multilines = this.string && _.str.lines(this.string).length > 1;
1312         } else {
1313             this.colspan = 1;
1314             this.width = '1%';
1315             this.decrease_max_width = 1;
1316             this.nowrap = true;
1317         }
1318     },
1319     render: function () {
1320         if (this['for'] && this.type !== 'label') {
1321             return QWeb.render(this.template, {widget: this['for']});
1322         }
1323         // Actual label widgets should not have a false and have type label
1324         return QWeb.render(this.template, {widget: this});
1325     },
1326     start: function() {
1327         this._super();
1328         var self = this;
1329         if (this['for'] && (this['for'].help || openerp.connection.debug)) {
1330             this.do_attach_tooltip(self['for']);
1331         }
1332         this.$element.find("label").dblclick(function() {
1333             var widget = self['for'] || self;
1334             openerp.log(widget.element_class , widget);
1335             window.w = widget;
1336         });
1337     }
1338 });
1339
1340 openerp.web.form.Field = openerp.web.form.Widget.extend(/** @lends openerp.web.form.Field# */{
1341     /**
1342      * @constructs openerp.web.form.Field
1343      * @extends openerp.web.form.Widget
1344      *
1345      * @param view
1346      * @param node
1347      */
1348     init: function(view, node) {
1349         this.name = node.attrs.name;
1350         this.value = undefined;
1351         view.fields[this.name] = this;
1352         view.fields_order.push(this.name);
1353         this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
1354         this.element_name = "field_" + this.name + "_" + this.type;
1355
1356         this._super(view, node);
1357
1358         if (node.attrs.nolabel != '1' && this.colspan > 1) {
1359             this.colspan--;
1360         }
1361         this.field = view.fields_view.fields[node.attrs.name] || {};
1362         this.string = node.attrs.string || this.field.string;
1363         this.help = node.attrs.help || this.field.help;
1364         this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
1365         this.readonly = this.modifiers['readonly'] === true;
1366         this.required = this.modifiers['required'] === true;
1367         this.invalid = this.dirty = false;
1368
1369         this.classname = 'oe_form_field_' + this.type;
1370     },
1371     start: function() {
1372         this._super.apply(this, arguments);
1373         if (this.field.translate) {
1374             this.view.translatable_fields.push(this);
1375             this.$element.addClass('oe_form_field_translatable');
1376             this.$element.find('.oe_field_translate').click(this.on_translate);
1377         }
1378         if (this.nolabel && openerp.connection.debug) {
1379             this.do_attach_tooltip(this, this.$element);
1380         }
1381     },
1382     set_value: function(value) {
1383         this.value = value;
1384         this.invalid = false;
1385         this.update_dom();
1386         this.on_value_changed();
1387     },
1388     set_value_from_ui: function() {
1389         this.on_value_changed();
1390     },
1391     on_value_changed: function() {
1392     },
1393     on_translate: function() {
1394         this.view.open_translate_dialog(this);
1395     },
1396     get_value: function() {
1397         return this.value;
1398     },
1399     is_valid: function() {
1400         return !this.invalid;
1401     },
1402     is_dirty: function() {
1403         return this.dirty && !this.readonly;
1404     },
1405     get_on_change_value: function() {
1406         return this.get_value();
1407     },
1408     update_dom: function(show_invalid) {
1409         this._super.apply(this, arguments);
1410         if (this.field.translate) {
1411             this.$element.find('.oe_field_translate').toggle(!!this.view.datarecord.id);
1412         }
1413         if (!this.disable_utility_classes) {
1414             this.$element.toggleClass('disabled', this.readonly);
1415             this.$element.toggleClass('required', this.required);
1416             if (show_invalid) {
1417                 this.$element.toggleClass('invalid', !this.is_valid());
1418             }
1419         }
1420     },
1421     on_ui_change: function() {
1422         this.dirty = true;
1423         this.validate();
1424         if (this.is_valid()) {
1425             this.set_value_from_ui();
1426             this.view.do_onchange(this);
1427             this.view.on_form_changed(true);
1428             this.view.do_notify_change();
1429         } else {
1430             this.update_dom(true);
1431         }
1432     },
1433     validate: function() {
1434         this.invalid = false;
1435     },
1436     focus: function($element) {
1437         if ($element) {
1438             setTimeout(function() {
1439                 $element.focus();
1440             }, 50);
1441         }
1442     },
1443     reset: function() {
1444         this.dirty = false;
1445     },
1446     get_definition_options: function() {
1447         if (!this.definition_options) {
1448             var str = this.node.attrs.options || '{}';
1449             this.definition_options = JSON.parse(str);
1450         }
1451         return this.definition_options;
1452     }
1453 });
1454
1455 openerp.web.form.FieldChar = openerp.web.form.Field.extend({
1456     template: 'FieldChar',
1457     init: function (view, node) {
1458         this._super(view, node);
1459         this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1460     },
1461     start: function() {
1462         this._super.apply(this, arguments);
1463         this.$element.find('input').change(this.on_ui_change);
1464     },
1465     set_value: function(value) {
1466         this._super.apply(this, arguments);
1467         var show_value = openerp.web.format_value(value, this, '');
1468         this.$element.find('input').val(show_value);
1469         return show_value;
1470     },
1471     update_dom: function() {
1472         this._super.apply(this, arguments);
1473         this.$element.find('input').prop('readonly', this.readonly);
1474     },
1475     set_value_from_ui: function() {
1476         this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1477         this._super();
1478     },
1479     validate: function() {
1480         this.invalid = false;
1481         try {
1482             var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1483             this.invalid = this.required && value === '';
1484         } catch(e) {
1485             this.invalid = true;
1486         }
1487     },
1488     focus: function($element) {
1489         this._super($element || this.$element.find('input:first'));
1490     }
1491 });
1492
1493 openerp.web.form.FieldID = openerp.web.form.FieldChar.extend({
1494     update_dom: function() {
1495         this._super.apply(this, arguments);
1496         this.$element.find('input').prop('readonly', true);
1497     }
1498 });
1499
1500 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1501     template: 'FieldEmail',
1502     start: function() {
1503         this._super.apply(this, arguments);
1504         this.$element.find('button').click(this.on_button_clicked);
1505     },
1506     on_button_clicked: function() {
1507         if (!this.value || !this.is_valid()) {
1508             this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1509         } else {
1510             location.href = 'mailto:' + this.value;
1511         }
1512     }
1513 });
1514
1515 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1516     template: 'FieldUrl',
1517     start: function() {
1518         this._super.apply(this, arguments);
1519         this.$element.find('button').click(this.on_button_clicked);
1520     },
1521     on_button_clicked: function() {
1522         if (!this.value) {
1523             this.do_warn("Resource error", "This resource is empty");
1524         } else {
1525             window.open(this.value);
1526         }
1527     }
1528 });
1529
1530 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1531     init: function (view, node) {
1532         this._super(view, node);
1533         if (node.attrs.digits) {
1534             this.digits = py.eval(node.attrs.digits).toJSON();
1535         } else {
1536             this.digits = view.fields_view.fields[node.attrs.name].digits;
1537         }
1538     },
1539     set_value: function(value) {
1540         if (value === false || value === undefined) {
1541             // As in GTK client, floats default to 0
1542             value = 0;
1543         }
1544         this._super.apply(this, [value]);
1545     }
1546 });
1547
1548 openerp.web.DateTimeWidget = openerp.web.OldWidget.extend({
1549     template: "web.datetimepicker",
1550     jqueryui_object: 'datetimepicker',
1551     type_of_date: "datetime",
1552     init: function(parent) {
1553         this._super(parent);
1554         this.name = parent.name;
1555     },
1556     start: function() {
1557         var self = this;
1558         this.$input = this.$element.find('input.oe_datepicker_master');
1559         this.$input_picker = this.$element.find('input.oe_datepicker_container');
1560         this.$input.change(this.on_change);
1561         this.picker({
1562             onSelect: this.on_picker_select,
1563             changeMonth: true,
1564             changeYear: true,
1565             showWeek: true,
1566             showButtonPanel: true
1567         });
1568         this.$element.find('img.oe_datepicker_trigger').click(function() {
1569             if (!self.readonly && !self.picker('widget').is(':visible')) {
1570                 self.picker('setDate', self.value ? openerp.web.auto_str_to_date(self.value) : new Date());
1571                 self.$input_picker.show();
1572                 self.picker('show');
1573                 self.$input_picker.hide();
1574             }
1575         });
1576         this.set_readonly(false);
1577         this.value = false;
1578     },
1579     picker: function() {
1580         return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1581     },
1582     on_picker_select: function(text, instance) {
1583         var date = this.picker('getDate');
1584         this.$input.val(date ? this.format_client(date) : '').change();
1585     },
1586     set_value: function(value) {
1587         this.value = value;
1588         this.$input.val(value ? this.format_client(value) : '');
1589     },
1590     get_value: function() {
1591         return this.value;
1592     },
1593     set_value_from_ui: function() {
1594         var value = this.$input.val() || false;
1595         this.value = this.parse_client(value);
1596     },
1597     set_readonly: function(readonly) {
1598         this.readonly = readonly;
1599         this.$input.prop('readonly', this.readonly);
1600         this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
1601     },
1602     is_valid: function(required) {
1603         var value = this.$input.val();
1604         if (value === "") {
1605             return !required;
1606         } else {
1607             try {
1608                 this.parse_client(value);
1609                 return true;
1610             } catch(e) {
1611                 return false;
1612             }
1613         }
1614     },
1615     parse_client: function(v) {
1616         return openerp.web.parse_value(v, {"widget": this.type_of_date});
1617     },
1618     format_client: function(v) {
1619         return openerp.web.format_value(v, {"widget": this.type_of_date});
1620     },
1621     on_change: function() {
1622         if (this.is_valid()) {
1623             this.set_value_from_ui();
1624         }
1625     }
1626 });
1627
1628 openerp.web.DateWidget = openerp.web.DateTimeWidget.extend({
1629     jqueryui_object: 'datepicker',
1630     type_of_date: "date"
1631 });
1632
1633 openerp.web.form.FieldDatetime = openerp.web.form.Field.extend({
1634     template: "EmptyComponent",
1635     build_widget: function() {
1636         return new openerp.web.DateTimeWidget(this);
1637     },
1638     start: function() {
1639         var self = this;
1640         this._super.apply(this, arguments);
1641         this.datewidget = this.build_widget();
1642         this.datewidget.on_change.add_last(this.on_ui_change);
1643         this.datewidget.appendTo(this.$element);
1644     },
1645     set_value: function(value) {
1646         this._super(value);
1647         this.datewidget.set_value(value);
1648     },
1649     get_value: function() {
1650         return this.datewidget.get_value();
1651     },
1652     update_dom: function() {
1653         this._super.apply(this, arguments);
1654         this.datewidget.set_readonly(this.readonly);
1655     },
1656     validate: function() {
1657         this.invalid = !this.datewidget.is_valid(this.required);
1658     },
1659     focus: function($element) {
1660         this._super($element || this.datewidget.$input);
1661     }
1662 });
1663
1664 openerp.web.form.FieldDate = openerp.web.form.FieldDatetime.extend({
1665     build_widget: function() {
1666         return new openerp.web.DateWidget(this);
1667     }
1668 });
1669
1670 openerp.web.form.FieldText = openerp.web.form.Field.extend({
1671     template: 'FieldText',
1672     start: function() {
1673         this._super.apply(this, arguments);
1674         this.$element.find('textarea').change(this.on_ui_change);
1675         this.resized = false;
1676     },
1677     set_value: function(value) {
1678         this._super.apply(this, arguments);
1679         var show_value = openerp.web.format_value(value, this, '');
1680         this.$element.find('textarea').val(show_value);
1681         if (!this.resized && this.view.options.resize_textareas) {
1682             this.do_resize(this.view.options.resize_textareas);
1683             this.resized = true;
1684         }
1685     },
1686     update_dom: function() {
1687         this._super.apply(this, arguments);
1688         this.$element.find('textarea').prop('readonly', this.readonly);
1689     },
1690     set_value_from_ui: function() {
1691         this.value = openerp.web.parse_value(this.$element.find('textarea').val(), this);
1692         this._super();
1693     },
1694     validate: function() {
1695         this.invalid = false;
1696         try {
1697             var value = openerp.web.parse_value(this.$element.find('textarea').val(), this, '');
1698             this.invalid = this.required && value === '';
1699         } catch(e) {
1700             this.invalid = true;
1701         }
1702     },
1703     focus: function($element) {
1704         this._super($element || this.$element.find('textarea:first'));
1705     },
1706     do_resize: function(max_height) {
1707         max_height = parseInt(max_height, 10);
1708         var $input = this.$element.find('textarea'),
1709             $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
1710             new_height;
1711         $div.text($input.val());
1712         _.each('font-family,font-size,white-space'.split(','), function(style) {
1713             $div.css(style, $input.css(style));
1714         });
1715         $div.appendTo($('body'));
1716         new_height = $div.height();
1717         if (new_height < 90) {
1718             new_height = 90;
1719         }
1720         if (!isNaN(max_height) && new_height > max_height) {
1721             new_height = max_height;
1722         }
1723         $div.remove();
1724         $input.height(new_height);
1725     },
1726     reset: function() {
1727         this.resized = false;
1728     }
1729 });
1730
1731 openerp.web.form.FieldBoolean = openerp.web.form.Field.extend({
1732     template: 'FieldBoolean',
1733     start: function() {
1734         var self = this;
1735         this._super.apply(this, arguments);
1736         this.$element.find('input').click(self.on_ui_change);
1737     },
1738     set_value: function(value) {
1739         this._super.apply(this, arguments);
1740         this.$element.find('input')[0].checked = value;
1741     },
1742     set_value_from_ui: function() {
1743         this.value = this.$element.find('input').is(':checked');
1744         this._super();
1745     },
1746     update_dom: function() {
1747         this._super.apply(this, arguments);
1748         this.$element.find('input').prop('disabled', this.readonly);
1749     },
1750     focus: function($element) {
1751         this._super($element || this.$element.find('input:first'));
1752     }
1753 });
1754
1755 openerp.web.form.FieldProgressBar = openerp.web.form.Field.extend({
1756     template: 'FieldProgressBar',
1757     start: function() {
1758         this._super.apply(this, arguments);
1759         this.$element.find('div').progressbar({
1760             value: this.value,
1761             disabled: this.readonly
1762         });
1763     },
1764     set_value: function(value) {
1765         this._super.apply(this, arguments);
1766         var show_value = Number(value);
1767         if (isNaN(show_value)) {
1768             show_value = 0;
1769         }
1770         var formatted_value = openerp.web.format_value(show_value, { type : 'float' }, '0');
1771         this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(formatted_value + '%');
1772     }
1773 });
1774
1775 openerp.web.form.FieldTextXml = openerp.web.form.Field.extend({
1776 // to replace view editor
1777 });
1778
1779 openerp.web.form.FieldSelection = openerp.web.form.Field.extend({
1780     template: 'FieldSelection',
1781     init: function(view, node) {
1782         var self = this;
1783         this._super(view, node);
1784         this.values = _.clone(this.field.selection);
1785         _.each(this.values, function(v, i) {
1786             if (v[0] === false && v[1] === '') {
1787                 self.values.splice(i, 1);
1788             }
1789         });
1790         this.values.unshift([false, '']);
1791     },
1792     start: function() {
1793         // Flag indicating whether we're in an event chain containing a change
1794         // event on the select, in order to know what to do on keyup[RETURN]:
1795         // * If the user presses [RETURN] as part of changing the value of a
1796         //   selection, we should just let the value change and not let the
1797         //   event broadcast further (e.g. to validating the current state of
1798         //   the form in editable list view, which would lead to saving the
1799         //   current row or switching to the next one)
1800         // * If the user presses [RETURN] with a select closed (side-effect:
1801         //   also if the user opened the select and pressed [RETURN] without
1802         //   changing the selected value), takes the action as validating the
1803         //   row
1804         var ischanging = false;
1805         this._super.apply(this, arguments);
1806         this.$element.find('select')
1807             .change(this.on_ui_change)
1808             .change(function () { ischanging = true; })
1809             .click(function () { ischanging = false; })
1810             .keyup(function (e) {
1811                 if (e.which !== 13 || !ischanging) { return; }
1812                 e.stopPropagation();
1813                 ischanging = false;
1814             });
1815     },
1816     set_value: function(value) {
1817         value = value === null ? false : value;
1818         value = value instanceof Array ? value[0] : value;
1819         this._super(value);
1820         var index = 0;
1821         for (var i = 0, ii = this.values.length; i < ii; i++) {
1822             if (this.values[i][0] === value) index = i;
1823         }
1824         this.$element.find('select')[0].selectedIndex = index;
1825     },
1826     set_value_from_ui: function() {
1827         this.value = this.values[this.$element.find('select')[0].selectedIndex][0];
1828         this._super();
1829     },
1830     update_dom: function() {
1831         this._super.apply(this, arguments);
1832         this.$element.find('select').prop('disabled', this.readonly);
1833     },
1834     validate: function() {
1835         var value = this.values[this.$element.find('select')[0].selectedIndex];
1836         this.invalid = !(value && !(this.required && value[0] === false));
1837     },
1838     focus: function($element) {
1839         this._super($element || this.$element.find('select:first'));
1840     }
1841 });
1842
1843 // jquery autocomplete tweak to allow html
1844 (function() {
1845     var proto = $.ui.autocomplete.prototype,
1846         initSource = proto._initSource;
1847
1848     function filter( array, term ) {
1849         var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1850         return $.grep( array, function(value) {
1851             return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1852         });
1853     }
1854
1855     $.extend( proto, {
1856         _initSource: function() {
1857             if ( this.options.html && $.isArray(this.options.source) ) {
1858                 this.source = function( request, response ) {
1859                     response( filter( this.options.source, request.term ) );
1860                 };
1861             } else {
1862                 initSource.call( this );
1863             }
1864         },
1865
1866         _renderItem: function( ul, item) {
1867             return $( "<li></li>" )
1868                 .data( "item.autocomplete", item )
1869                 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1870                 .appendTo( ul );
1871         }
1872     });
1873 })();
1874
1875 openerp.web.form.dialog = function(content, options) {
1876     options = _.extend({
1877         width: '90%',
1878         height: 'auto',
1879         min_width: '800px'
1880     }, options || {});
1881     var dialog = new openerp.web.Dialog(null, options, content).open();
1882     return dialog.$element;
1883 };
1884
1885 openerp.web.form.FieldMany2One = openerp.web.form.Field.extend({
1886     template: 'FieldMany2One',
1887     init: function(view, node) {
1888         this._super(view, node);
1889         this.limit = 7;
1890         this.value = null;
1891         this.cm_id = _.uniqueId('m2o_cm_');
1892         this.last_search = [];
1893         this.tmp_value = undefined;
1894     },
1895     start: function() {
1896         this._super();
1897         var self = this;
1898         this.$input = this.$element.find("input");
1899         this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1900         this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1901
1902         // context menu
1903         var init_context_menu_def = $.Deferred().then(function(e) {
1904             var rdataset = new openerp.web.DataSetStatic(self, "ir.values", self.build_context());
1905             rdataset.call("get", ['action', 'client_action_relate',
1906                 [[self.field.relation, false]], false, rdataset.get_context()], false, 0)
1907                 .then(function(result) {
1908                 self.related_entries = result;
1909
1910                 var $cmenu = $("#" + self.cm_id);
1911                 $cmenu.append(QWeb.render("FieldMany2One.context_menu", {widget: self}));
1912                 var bindings = {};
1913                 bindings[self.cm_id + "_search"] = function() {
1914                     if (self.readonly)
1915                         return;
1916                     self._search_create_popup("search");
1917                 };
1918                 bindings[self.cm_id + "_create"] = function() {
1919                     if (self.readonly)
1920                         return;
1921                     self._search_create_popup("form");
1922                 };
1923                 bindings[self.cm_id + "_open"] = function() {
1924                     if (!self.value) {
1925                         return;
1926                     }
1927                     var pop = new openerp.web.form.FormOpenPopup(self.view);
1928                     pop.show_element(
1929                         self.field.relation,
1930                         self.value[0],
1931                         self.build_context(),
1932                         {
1933                             title: _t("Open: ") + (self.string || self.name)
1934                         }
1935                     );
1936                     pop.on_write_completed.add_last(function() {
1937                         self.set_value(self.value[0]);
1938                     });
1939                 };
1940                 _.each(_.range(self.related_entries.length), function(i) {
1941                     bindings[self.cm_id + "_related_" + i] = function() {
1942                         self.open_related(self.related_entries[i]);
1943                     };
1944                 });
1945                 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'noRightClick': true,
1946                     bindings: bindings, itemStyle: {"color": ""},
1947                     onContextMenu: function() {
1948                         if(self.value) {
1949                             $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1950                         } else {
1951                             $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1952                         }
1953                         if (!self.readonly) {
1954                             $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1955                         } else {
1956                             $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
1957                         }
1958                         return true;
1959                     }, menuStyle: {width: "200px"}
1960                 });
1961                 $.async_when().then(function() {self.$menu_btn.trigger(e);});
1962             });
1963         });
1964         var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
1965         this.$menu_btn.click(ctx_callback);
1966
1967         // some behavior for input
1968         this.$input.keyup(function() {
1969             if (self.$input.val() === "") {
1970                 self._change_int_value(null);
1971             } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1972                 self._change_int_value(undefined);
1973             }
1974         });
1975         this.$drop_down.click(function() {
1976             if (self.readonly)
1977                 return;
1978             if (self.$input.autocomplete("widget").is(":visible")) {
1979                 self.$input.autocomplete("close");
1980             } else {
1981                 if (self.value) {
1982                     self.$input.autocomplete("search", "");
1983                 } else {
1984                     self.$input.autocomplete("search");
1985                 }
1986                 self.$input.focus();
1987             }
1988         });
1989         var anyoneLoosesFocus = function() {
1990             if (!self.$input.is(":focus") &&
1991                     !self.$input.autocomplete("widget").is(":visible") &&
1992                     !self.value) {
1993                 if (self.value === undefined && self.last_search.length > 0) {
1994                     self._change_int_ext_value(self.last_search[0]);
1995                 } else {
1996                     self._change_int_ext_value(null);
1997                 }
1998             }
1999         };
2000         this.$input.focusout(anyoneLoosesFocus);
2001
2002         var isSelecting = false;
2003         // autocomplete
2004         this.$input.autocomplete({
2005             source: function(req, resp) { self.get_search_result(req, resp); },
2006             select: function(event, ui) {
2007                 isSelecting = true;
2008                 var item = ui.item;
2009                 if (item.id) {
2010                     self._change_int_value([item.id, item.name]);
2011                 } else if (item.action) {
2012                     self._change_int_value(undefined);
2013                     item.action();
2014                     return false;
2015                 }
2016             },
2017             focus: function(e, ui) {
2018                 e.preventDefault();
2019             },
2020             html: true,
2021             close: anyoneLoosesFocus,
2022             minLength: 0,
2023             delay: 0
2024         });
2025         // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2026         this.$input.keyup(function(e) {
2027             if (e.which === 13) {
2028                 if (isSelecting)
2029                     e.stopPropagation();
2030             }
2031             isSelecting = false;
2032         });
2033     },
2034     // autocomplete component content handling
2035     get_search_result: function(request, response) {
2036         var search_val = request.term;
2037         var self = this;
2038
2039         if (this.abort_last) {
2040             this.abort_last();
2041             delete this.abort_last;
2042         }
2043         var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2044
2045         dataset.name_search(search_val, self.build_domain(), 'ilike',
2046                 this.limit + 1, function(data) {
2047             self.last_search = data;
2048             // possible selections for the m2o
2049             var values = _.map(data, function(x) {
2050                 return {
2051                     label: _.str.escapeHTML(x[1]),
2052                     value:x[1],
2053                     name:x[1],
2054                     id:x[0]
2055                 };
2056             });
2057
2058             // search more... if more results that max
2059             if (values.length > self.limit) {
2060                 var open_search_popup = function(data) {
2061                     self._change_int_value(null);
2062                     self._search_create_popup("search", data);
2063                 };
2064                 values = values.slice(0, self.limit);
2065                 values.push({label: _t("<em>   Search More...</em>"), action: function() {
2066                     if (!search_val) {
2067                         // search optimisation - in case user didn't enter any text we
2068                         // do not need to prefilter records; for big datasets (ex: more
2069                         // that 10.000 records) calling name_search() could be very very
2070                         // expensive!
2071                         open_search_popup();
2072                         return;
2073                     }
2074                     dataset.name_search(search_val, self.build_domain(),
2075                                         'ilike', false, open_search_popup);
2076                 }});
2077             }
2078             // quick create
2079             var raw_result = _(data.result).map(function(x) {return x[1];});
2080             if (search_val.length > 0 &&
2081                 !_.include(raw_result, search_val) &&
2082                 (!self.value || search_val !== self.value[1])) {
2083                 values.push({label: _.str.sprintf(_t('<em>   Create "<strong>%s</strong>"</em>'),
2084                         $('<span />').text(search_val).html()), action: function() {
2085                     self._quick_create(search_val);
2086                 }});
2087             }
2088             // create...
2089             values.push({label: _t("<em>   Create and Edit...</em>"), action: function() {
2090                 self._change_int_value(null);
2091                 self._search_create_popup("form", undefined, {"default_name": search_val});
2092             }});
2093
2094             response(values);
2095         });
2096         this.abort_last = dataset.abort_last;
2097     },
2098     _quick_create: function(name) {
2099         var self = this;
2100         var slow_create = function () {
2101             self._change_int_value(null);
2102             self._search_create_popup("form", undefined, {"default_name": name});
2103         };
2104         if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2105             var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2106             dataset.name_create(name, function(data) {
2107                 self._change_int_ext_value(data);
2108             }).fail(function(error, event) {
2109                 event.preventDefault();
2110                 slow_create();
2111             });
2112         } else
2113             slow_create();
2114     },
2115     // all search/create popup handling
2116     _search_create_popup: function(view, ids, context) {
2117         var self = this;
2118         var pop = new openerp.web.form.SelectCreatePopup(this);
2119         pop.select_element(
2120             self.field.relation,
2121             {
2122                 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2123                 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2124                 initial_view: view,
2125                 disable_multiple_selection: true
2126             },
2127             self.build_domain(),
2128             new openerp.web.CompoundContext(self.build_context(), context || {})
2129         );
2130         pop.on_select_elements.add(function(element_ids) {
2131             var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
2132             dataset.name_get([element_ids[0]], function(data) {
2133                 self._change_int_ext_value(data[0]);
2134             });
2135         });
2136     },
2137     _change_int_ext_value: function(value) {
2138         this._change_int_value(value);
2139         this.$input.val(this.value ? this.value[1] : "");
2140     },
2141     _change_int_value: function(value) {
2142         this.value = value;
2143         var back_orig_value = this.original_value;
2144         if (this.value === null || this.value) {
2145             this.original_value = this.value;
2146         }
2147         if (back_orig_value === undefined) { // first use after a set_value()
2148             return;
2149         }
2150         if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
2151                 !== (this.value ? this.value[0] : null))) {
2152             this.on_ui_change();
2153         }
2154     },
2155     set_value: function(value) {
2156         value = value || null;
2157         this.invalid = false;
2158         var self = this;
2159         this.tmp_value = value;
2160         self.update_dom();
2161         self.on_value_changed();
2162         var real_set_value = function(rval) {
2163             self.tmp_value = undefined;
2164             self.value = rval;
2165             self.original_value = undefined;
2166             self._change_int_ext_value(rval);
2167         };
2168         if (value && !(value instanceof Array)) {
2169             // name_get in a m2o does not use the context of the field
2170             var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2171             dataset.name_get([value], function(data) {
2172                 real_set_value(data[0]);
2173             }).fail(function() {self.tmp_value = undefined;});
2174         } else {
2175             $.async_when().then(function() {real_set_value(value);});
2176         }
2177     },
2178     get_value: function() {
2179         if (this.tmp_value !== undefined) {
2180             if (this.tmp_value instanceof Array) {
2181                 return this.tmp_value[0];
2182             }
2183             return this.tmp_value ? this.tmp_value : false;
2184         }
2185         if (this.value === undefined)
2186             return this.original_value ? this.original_value[0] : false;
2187         return this.value ? this.value[0] : false;
2188     },
2189     validate: function() {
2190         this.invalid = false;
2191         var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
2192         if (val === null) {
2193             this.invalid = this.required;
2194         }
2195     },
2196     open_related: function(related) {
2197         var self = this;
2198         if (!self.value)
2199             return;
2200         var additional_context = {
2201                 active_id: self.value[0],
2202                 active_ids: [self.value[0]],
2203                 active_model: self.field.relation
2204         };
2205         self.rpc("/web/action/load", {
2206             action_id: related[2].id,
2207             context: additional_context
2208         }, function(result) {
2209             result.result.context = _.extend(result.result.context || {}, additional_context);
2210             self.do_action(result.result);
2211         });
2212     },
2213     focus: function ($element) {
2214         this._super($element || this.$input);
2215     },
2216     update_dom: function() {
2217         this._super.apply(this, arguments);
2218         this.$input.prop('readonly', this.readonly);
2219     }
2220 });
2221
2222 /*
2223 # Values: (0, 0,  { fields })    create
2224 #         (1, ID, { fields })    update
2225 #         (2, ID)                remove (delete)
2226 #         (3, ID)                unlink one (target id or target of relation)
2227 #         (4, ID)                link
2228 #         (5)                    unlink all (only valid for one2many)
2229 */
2230 var commands = {
2231     // (0, _, {values})
2232     CREATE: 0,
2233     'create': function (values) {
2234         return [commands.CREATE, false, values];
2235     },
2236     // (1, id, {values})
2237     UPDATE: 1,
2238     'update': function (id, values) {
2239         return [commands.UPDATE, id, values];
2240     },
2241     // (2, id[, _])
2242     DELETE: 2,
2243     'delete': function (id) {
2244         return [commands.DELETE, id, false];
2245     },
2246     // (3, id[, _]) removes relation, but not linked record itself
2247     FORGET: 3,
2248     'forget': function (id) {
2249         return [commands.FORGET, id, false];
2250     },
2251     // (4, id[, _])
2252     LINK_TO: 4,
2253     'link_to': function (id) {
2254         return [commands.LINK_TO, id, false];
2255     },
2256     // (5[, _[, _]])
2257     DELETE_ALL: 5,
2258     'delete_all': function () {
2259         return [5, false, false];
2260     },
2261     // (6, _, ids) replaces all linked records with provided ids
2262     REPLACE_WITH: 6,
2263     'replace_with': function (ids) {
2264         return [6, false, ids];
2265     }
2266 };
2267 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2268     template: 'FieldOne2Many',
2269     multi_selection: false,
2270     init: function(view, node) {
2271         this._super(view, node);
2272         this.is_loaded = $.Deferred();
2273         this.initial_is_loaded = this.is_loaded;
2274         this.is_setted = $.Deferred();
2275         this.form_last_update = $.Deferred();
2276         this.init_form_last_update = this.form_last_update;
2277         this.disable_utility_classes = true;
2278     },
2279     start: function() {
2280         this._super.apply(this, arguments);
2281
2282         var self = this;
2283
2284         this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2285         this.dataset.o2m = this;
2286         this.dataset.parent_view = this.view;
2287         this.dataset.child_name = this.name;
2288         //this.dataset.child_name = 
2289         this.dataset.on_change.add_last(function() {
2290             self.trigger_on_change();
2291         });
2292
2293         this.is_setted.then(function() {
2294             self.load_views();
2295         });
2296     },
2297     trigger_on_change: function() {
2298         var tmp = this.doing_on_change;
2299         this.doing_on_change = true;
2300         this.on_ui_change();
2301         this.doing_on_change = tmp;
2302     },
2303     is_readonly: function() {
2304         return this.readonly || this.force_readonly;
2305     },
2306     load_views: function() {
2307         var self = this;
2308         
2309         var modes = this.node.attrs.mode;
2310         modes = !!modes ? modes.split(",") : ["tree"];
2311         var views = [];
2312         _.each(modes, function(mode) {
2313             var view = {
2314                 view_id: false,
2315                 view_type: mode == "tree" ? "list" : mode,
2316                 options: { sidebar : false }
2317             };
2318             if (self.field.views && self.field.views[mode]) {
2319                 view.embedded_view = self.field.views[mode];
2320             }
2321             if(view.view_type === "list") {
2322                 view.options.selectable = self.multi_selection;
2323                 if (self.is_readonly()) {
2324                     view.options.addable = null;
2325                     view.options.deletable = null;
2326                     view.options.isClarkGable = false;
2327                 }
2328             } else if (view.view_type === "form") {
2329                 if (self.is_readonly()) {
2330                     view.view_type = 'page';
2331                 }
2332                 view.options.not_interactible_on_create = true;
2333             }
2334             views.push(view);
2335         });
2336         this.views = views;
2337
2338         this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views, {});
2339         this.viewmanager.template = 'One2Many.viewmanager';
2340         this.viewmanager.registry = openerp.web.views.extend({
2341             list: 'openerp.web.form.One2ManyListView',
2342             form: 'openerp.web.form.One2ManyFormView',
2343             page: 'openerp.web.PageView'
2344         });
2345         var once = $.Deferred().then(function() {
2346             self.init_form_last_update.resolve();
2347         });
2348         var def = $.Deferred().then(function() {
2349             self.initial_is_loaded.resolve();
2350         });
2351         this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2352             if (view_type == "list") {
2353                 controller.o2m = self;
2354                 if (self.is_readonly())
2355                     controller.set_editable(false);
2356             } else if (view_type == "form" || view_type == 'page') {
2357                 if (view_type == 'page' || self.is_readonly()) {
2358                     $(".oe_form_buttons", controller.$element).children().remove();
2359                 }
2360                 controller.on_record_loaded.add_last(function() {
2361                     once.resolve();
2362                 });
2363                 controller.on_pager_action.add_first(function() {
2364                     self.save_any_view();
2365                 });
2366             } else if (view_type == "graph") {
2367                 self.reload_current_view()
2368             }
2369             def.resolve();
2370         });
2371         this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2372             $.when(self.save_any_view()).then(function() {
2373                 if(n_mode === "list")
2374                     $.async_when().then(function() {self.reload_current_view();});
2375             });
2376         });
2377         this.is_setted.then(function() {
2378             $.async_when().then(function () {
2379                 self.viewmanager.appendTo(self.$element);
2380             });
2381         });
2382         return def;
2383     },
2384     reload_current_view: function() {
2385         var self = this;
2386         return self.is_loaded = self.is_loaded.pipe(function() {
2387             var active_view = self.viewmanager.active_view;
2388             var view = self.viewmanager.views[active_view].controller;
2389             if(active_view === "list") {
2390                 return view.reload_content();
2391             } else if (active_view === "form" || active_view === 'page') {
2392                 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2393                     self.dataset.index = 0;
2394                 }
2395                 var act = function() {
2396                     return view.do_show();
2397                 };
2398                 self.form_last_update = self.form_last_update.pipe(act, act);
2399                 return self.form_last_update;
2400             } else if (active_view === "graph") {
2401                 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2402             }
2403         }, undefined);
2404     },
2405     set_value: function(value) {
2406         value = value || [];
2407         var self = this;
2408         this.dataset.reset_ids([]);
2409         if(value.length >= 1 && value[0] instanceof Array) {
2410             var ids = [];
2411             _.each(value, function(command) {
2412                 var obj = {values: command[2]};
2413                 switch (command[0]) {
2414                     case commands.CREATE:
2415                         obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2416                         obj.defaults = {};
2417                         self.dataset.to_create.push(obj);
2418                         self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2419                         ids.push(obj.id);
2420                         return;
2421                     case commands.UPDATE:
2422                         obj['id'] = command[1];
2423                         self.dataset.to_write.push(obj);
2424                         self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2425                         ids.push(obj.id);
2426                         return;
2427                     case commands.DELETE:
2428                         self.dataset.to_delete.push({id: command[1]});
2429                         return;
2430                     case commands.LINK_TO:
2431                         ids.push(command[1]);
2432                         return;
2433                     case commands.DELETE_ALL:
2434                         self.dataset.delete_all = true;
2435                         return;
2436                 }
2437             });
2438             this._super(ids);
2439             this.dataset.set_ids(ids);
2440         } else if (value.length >= 1 && typeof(value[0]) === "object") {
2441             var ids = [];
2442             this.dataset.delete_all = true;
2443             _.each(value, function(command) {
2444                 var obj = {values: command};
2445                 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2446                 obj.defaults = {};
2447                 self.dataset.to_create.push(obj);
2448                 self.dataset.cache.push(_.clone(obj));
2449                 ids.push(obj.id);
2450             });
2451             this._super(ids);
2452             this.dataset.set_ids(ids);
2453         } else {
2454             this._super(value);
2455             this.dataset.reset_ids(value);
2456         }
2457         if (this.dataset.index === null && this.dataset.ids.length > 0) {
2458             this.dataset.index = 0;
2459         }
2460         self.is_setted.resolve();
2461         return self.reload_current_view();
2462     },
2463     get_value: function() {
2464         var self = this;
2465         if (!this.dataset)
2466             return [];
2467         this.save_any_view();
2468         var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2469         val = val.concat(_.map(this.dataset.ids, function(id) {
2470             var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2471             if (alter_order) {
2472                 return commands.create(alter_order.values);
2473             }
2474             alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2475             if (alter_order) {
2476                 return commands.update(alter_order.id, alter_order.values);
2477             }
2478             return commands.link_to(id);
2479         }));
2480         return val.concat(_.map(
2481             this.dataset.to_delete, function(x) {
2482                 return commands['delete'](x.id);}));
2483     },
2484     save_any_view: function() {
2485         if (this.doing_on_change)
2486             return false;
2487         return this.session.synchronized_mode(_.bind(function() {
2488                 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2489                     this.viewmanager.views[this.viewmanager.active_view] &&
2490                     this.viewmanager.views[this.viewmanager.active_view].controller) {
2491                     var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2492                     if (this.viewmanager.active_view === "form") {
2493                         if (!view.is_initialized.isResolved()) {
2494                             return false;
2495                         }
2496                         var res = $.when(view.do_save());
2497                         if (!res.isResolved() && !res.isRejected()) {
2498                             console.warn("Asynchronous get_value() is not supported in form view.");
2499                         }
2500                         return res;
2501                     } else if (this.viewmanager.active_view === "list") {
2502                         var res = $.when(view.ensure_saved());
2503                         if (!res.isResolved() && !res.isRejected()) {
2504                             console.warn("Asynchronous get_value() is not supported in list view.");
2505                         }
2506                         return res;
2507                     }
2508                 }
2509                 return false;
2510             }, this));
2511     },
2512     is_valid: function() {
2513         if (!this.viewmanager.views[this.viewmanager.active_view])
2514             return true;
2515         var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2516         switch (this.viewmanager.active_view) {
2517         case 'form':
2518             return _(view.fields).chain()
2519                 .invoke('is_valid')
2520                 .all(_.identity)
2521                 .value();
2522             break;
2523         case 'list':
2524             return view.is_valid();
2525         }
2526         return true;
2527     },
2528     is_dirty: function() {
2529         this.save_any_view();
2530         return this._super();
2531     },
2532     update_dom: function() {
2533         this._super.apply(this, arguments);
2534         var self = this;
2535         if (this.previous_readonly !== this.readonly) {
2536             this.previous_readonly = this.readonly;
2537             if (this.viewmanager) {
2538                 this.is_loaded = this.is_loaded.pipe(function() {
2539                     self.viewmanager.stop();
2540                     return $.when(self.load_views()).then(function() {
2541                         self.reload_current_view();
2542                     });
2543                 });
2544             }
2545         }
2546     }
2547 });
2548
2549 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2550     get_context: function() {
2551         this.context = this.o2m.build_context([this.o2m.name]);
2552         return this.context;
2553     }
2554 });
2555
2556 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2557     _template: 'One2Many.listview',
2558     init: function (parent, dataset, view_id, options) {
2559         this._super(parent, dataset, view_id, _.extend(options || {}, {
2560             ListType: openerp.web.form.One2ManyList
2561         }));
2562     },
2563     is_valid: function () {
2564         var form;
2565         // A list not being edited is always valid
2566         if (!(form = this.first_edition_form())) {
2567             return true;
2568         }
2569         // If the form has not been modified, the view can only be valid
2570         // NB: is_dirty will also be set on defaults/onchanges/whatever?
2571         // oe_form_dirty seems to only be set on actual user actions
2572         if (!form.$element.is('.oe_form_dirty')) {
2573             return true;
2574         }
2575
2576         // Otherwise validate internal form
2577         return _(form.fields).chain()
2578             .invoke(function () {
2579                 this.validate();
2580                 this.update_dom(true);
2581                 return this.is_valid();
2582             })
2583             .all(_.identity)
2584             .value();
2585     },
2586     first_edition_form: function () {
2587         var get_form = function (group_or_list) {
2588             if (group_or_list.edition) {
2589                 return group_or_list.edition_form;
2590             }
2591             return _(group_or_list.children).chain()
2592                 .map(get_form)
2593                 .compact()
2594                 .first()
2595                 .value();
2596         };
2597         return get_form(this.groups);
2598     },
2599     do_add_record: function () {
2600         if (this.options.editable) {
2601             this._super.apply(this, arguments);
2602         } else {
2603             var self = this;
2604             var pop = new openerp.web.form.SelectCreatePopup(this);
2605             pop.on_default_get.add(self.dataset.on_default_get);
2606             pop.select_element(
2607                 self.o2m.field.relation,
2608                 {
2609                     title: _t("Create: ") + self.name,
2610                     initial_view: "form",
2611                     alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2612                     create_function: function(data, callback, error_callback) {
2613                         return self.o2m.dataset.create(data).then(function(r) {
2614                             self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2615                             self.o2m.dataset.on_change();
2616                         }).then(callback, error_callback);
2617                     },
2618                     read_function: function() {
2619                         return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2620                     },
2621                     parent_view: self.o2m.view,
2622                     child_name: self.o2m.name,
2623                     form_view_options: {'not_interactible_on_create':true}
2624                 },
2625                 self.o2m.build_domain(),
2626                 self.o2m.build_context()
2627             );
2628             pop.on_select_elements.add_last(function() {
2629                 self.o2m.reload_current_view();
2630             });
2631         }
2632     },
2633     do_activate_record: function(index, id) {
2634         var self = this;
2635         var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2636         pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2637             title: _t("Open: ") + self.name,
2638             auto_write: false,
2639             alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2640             parent_view: self.o2m.view,
2641             child_name: self.o2m.name,
2642             read_function: function() {
2643                 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2644             },
2645             form_view_options: {'not_interactible_on_create':true},
2646             readonly: self.o2m.is_readonly()
2647         });
2648         pop.dataset.call_button = function() {
2649             var button_result = self.o2m.dataset.call_button.apply(self.o2m.dataset, arguments);
2650             self.o2m.reload_current_view();
2651             return button_result;
2652         };
2653         pop.on_write.add(function(id, data) {
2654             self.o2m.dataset.write(id, data, {}, function(r) {
2655                 self.o2m.reload_current_view();
2656             });
2657         });
2658     },
2659     do_button_action: function (name, id, callback) {
2660         var self = this;
2661         var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
2662         return this._super(name, id, _.bind(def.resolve, def));
2663     }
2664 });
2665 openerp.web.form.One2ManyList = openerp.web.ListView.List.extend({
2666     render_row_as_form: function () {
2667         var self = this;
2668         return this._super.apply(this, arguments).then(function () {
2669             self.setup_save_on_row_blur();
2670         });
2671     },
2672     bind_blur_focus: function (new_row, onblur, onfocus) {
2673         if (new_row.addEventListener) {
2674             new_row.addEventListener('blur', onblur, true);
2675             new_row.addEventListener('focus', onfocus, true);
2676         } else {
2677             new_row.onfocusout = onblur;
2678             new_row.onfocusin = onfocus;
2679         }
2680     },
2681     setup_save_on_row_blur: function () {
2682         var self = this;
2683         var form = this.edition_form;
2684         this.bind_blur_focus(this.edition_form.$element[0], function () {
2685             self._save_row_timeout = setTimeout(function () {
2686                 if (form.widget_is_stopped) {
2687                     // Saved or cancelled already, maybe?
2688                     return;
2689                 }
2690                 self.view.ensure_saved();
2691             }, 0);
2692         }, function () {
2693             clearTimeout(self._save_row_timeout);
2694             delete self._save_row_timeout;
2695         });
2696     }
2697 });
2698
2699 openerp.web.form.One2ManyFormView = openerp.web.FormView.extend({
2700     form_template: 'One2Many.formview',
2701     on_loaded: function(data) {
2702         this._super(data);
2703         var self = this;
2704         this.$form_header.find('button.oe_form_button_create').click(function() {
2705             self.do_save().then(self.on_button_new);
2706         });
2707     },
2708     do_notify_change: function() {
2709         if (this.dataset.parent_view) {
2710             this.dataset.parent_view.do_notify_change();
2711         } else {
2712             this._super.apply(this, arguments);
2713         }
2714     }
2715 });
2716
2717 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2718     template: 'FieldMany2Many',
2719     multi_selection: false,
2720     init: function(view, node) {
2721         this._super(view, node);
2722         this.list_id = _.uniqueId("many2many");
2723         this.is_loaded = $.Deferred();
2724         this.initial_is_loaded = this.is_loaded;
2725         this.is_setted = $.Deferred();
2726     },
2727     start: function() {
2728         this._super.apply(this, arguments);
2729
2730         var self = this;
2731
2732         this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2733         this.dataset.m2m = this;
2734         this.dataset.on_unlink.add_last(function(ids) {
2735             self.on_ui_change();
2736         });
2737         
2738         this.is_setted.then(function() {
2739             self.load_view();
2740         });
2741     },
2742     set_value: function(value) {
2743         value = value || [];
2744         if (value.length >= 1 && value[0] instanceof Array) {
2745             value = value[0][2];
2746         }
2747         this._super(value);
2748         this.dataset.set_ids(value);
2749         var self = this;
2750         self.reload_content();
2751         this.is_setted.resolve();
2752     },
2753     get_value: function() {
2754         return [commands.replace_with(this.dataset.ids)];
2755     },
2756     validate: function() {
2757         this.invalid = this.required && _(this.dataset.ids).isEmpty();
2758     },
2759     is_readonly: function() {
2760         return this.readonly || this.force_readonly;
2761     },
2762     load_view: function() {
2763         var self = this;
2764         this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2765                     'addable': self.is_readonly() ? null : _t("Add"),
2766                     'deletable': self.is_readonly() ? false : true,
2767                     'selectable': self.multi_selection,
2768                     'isClarkGable': self.is_readonly() ? false : true
2769             });
2770         var embedded = (this.field.views || {}).tree;
2771         if (embedded) {
2772             this.list_view.set_embedded_view(embedded);
2773         }
2774         this.list_view.m2m_field = this;
2775         var loaded = $.Deferred();
2776         this.list_view.on_loaded.add_last(function() {
2777             self.initial_is_loaded.resolve();
2778             loaded.resolve();
2779         });
2780         $.async_when().then(function () {
2781             self.list_view.appendTo($("#" + self.list_id));
2782         });
2783         return loaded;
2784     },
2785     reload_content: function() {
2786         var self = this;
2787         this.is_loaded = this.is_loaded.pipe(function() {
2788             return self.list_view.reload_content();
2789         });
2790     },
2791     update_dom: function() {
2792         this._super.apply(this, arguments);
2793         var self = this;
2794         if (this.previous_readonly !== this.readonly) {
2795             this.previous_readonly = this.readonly;
2796             if (this.list_view) {
2797                 this.is_loaded = this.is_loaded.pipe(function() {
2798                     self.list_view.stop();
2799                     return $.when(self.load_view()).then(function() {
2800                         self.reload_content();
2801                     });
2802                 });
2803             }
2804         }
2805     }
2806 });
2807
2808 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2809     get_context: function() {
2810         this.context = this.m2m.build_context();
2811         return this.context;
2812     }
2813 });
2814
2815 /**
2816  * @class
2817  * @extends openerp.web.ListView
2818  */
2819 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2820     do_add_record: function () {
2821         var pop = new openerp.web.form.SelectCreatePopup(this);
2822         pop.select_element(
2823             this.model,
2824             {
2825                 title: _t("Add: ") + this.name
2826             },
2827             new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2828             this.m2m_field.build_context()
2829         );
2830         var self = this;
2831         pop.on_select_elements.add(function(element_ids) {
2832             _.each(element_ids, function(element_id) {
2833                 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2834                     self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2835                     self.m2m_field.on_ui_change();
2836                     self.reload_content();
2837                 }
2838             });
2839         });
2840     },
2841     do_activate_record: function(index, id) {
2842         var self = this;
2843         var pop = new openerp.web.form.FormOpenPopup(this);
2844         pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
2845             title: _t("Open: ") + this.name,
2846             readonly: this.widget_parent.is_readonly()
2847         });
2848         pop.on_write_completed.add_last(function() {
2849             self.reload_content();
2850         });
2851     }
2852 });
2853
2854 /**
2855  * @class
2856  * @extends openerp.web.OldWidget
2857  */
2858 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2859     template: "SelectCreatePopup",
2860     /**
2861      * options:
2862      * - initial_ids
2863      * - initial_view: form or search (default search)
2864      * - disable_multiple_selection
2865      * - alternative_form_view
2866      * - create_function (defaults to a naive saving behavior)
2867      * - parent_view
2868      * - child_name
2869      * - form_view_options
2870      * - list_view_options
2871      * - read_function
2872      */
2873     select_element: function(model, options, domain, context) {
2874         var self = this;
2875         this.model = model;
2876         this.domain = domain || [];
2877         this.context = context || {};
2878         this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2879             return self.create_row.apply(self, arguments);
2880         }, read_function: null});
2881         this.initial_ids = this.options.initial_ids;
2882         this.created_elements = [];
2883         this.render_element();
2884         openerp.web.form.dialog(this.$element, {
2885             close: function() {
2886                 self.check_exit();
2887             },
2888             title: options.title || ""
2889         });
2890         this.start();
2891     },
2892     start: function() {
2893         this._super();
2894         var self = this;
2895         this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2896             this.context);
2897         this.dataset.create_function = function() {
2898             return self.options.create_function.apply(null, arguments).then(function(r) {
2899                 self.created_elements.push(r.result);
2900             });
2901         };
2902         this.dataset.write_function = function() {
2903             return self.write_row.apply(self, arguments);
2904         };
2905         this.dataset.read_function = this.options.read_function;
2906         this.dataset.parent_view = this.options.parent_view;
2907         this.dataset.child_name = this.options.child_name;
2908         this.dataset.on_default_get.add(this.on_default_get);
2909         if (this.options.initial_view == "search") {
2910             self.rpc('/web/session/eval_domain_and_context', {
2911                 domains: [],
2912                 contexts: [this.context]
2913             }, function (results) {
2914                 var search_defaults = {};
2915                 _.each(results.context, function (value, key) {
2916                     var match = /^search_default_(.*)$/.exec(key);
2917                     if (match) {
2918                         search_defaults[match[1]] = value;
2919                     }
2920                 });
2921                 self.setup_search_view(search_defaults);
2922             });
2923         } else { // "form"
2924             this.new_object();
2925         }
2926     },
2927     stop: function () {
2928         this.$element.dialog('close');
2929         this._super();
2930     },
2931     setup_search_view: function(search_defaults) {
2932         var self = this;
2933         if (this.searchview) {
2934             this.searchview.stop();
2935         }
2936         this.searchview = new openerp.web.SearchView(this,
2937                 this.dataset, false,  search_defaults);
2938         this.searchview.on_search.add(function(domains, contexts, groupbys) {
2939             if (self.initial_ids) {
2940                 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2941                     contexts, groupbys);
2942                 self.initial_ids = undefined;
2943             } else {
2944                 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
2945             }
2946         });
2947         this.searchview.on_loaded.add_last(function () {
2948             self.view_list = new openerp.web.form.SelectCreateListView(self,
2949                     self.dataset, false,
2950                     _.extend({'deletable': false,
2951                         'selectable': !self.options.disable_multiple_selection
2952                     }, self.options.list_view_options || {}));
2953             self.view_list.popup = self;
2954             self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2955                 self.view_list.do_show();
2956             }).pipe(function() {
2957                 self.searchview.do_search();
2958             });
2959             self.view_list.on_loaded.add_last(function() {
2960                 var $buttons = self.view_list.$element.find(".oe-actions");
2961                 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
2962                 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2963                 $cbutton.click(function() {
2964                     self.stop();
2965                 });
2966                 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2967                 if(self.options.disable_multiple_selection) {
2968                     $sbutton.hide();
2969                 }
2970                 $sbutton.click(function() {
2971                     self.on_select_elements(self.selected_ids);
2972                     self.stop();
2973                 });
2974             });
2975         });
2976         this.searchview.appendTo($("#" + this.element_id + "_search"));
2977     },
2978     do_search: function(domains, contexts, groupbys) {
2979         var self = this;
2980         this.rpc('/web/session/eval_domain_and_context', {
2981             domains: domains || [],
2982             contexts: contexts || [],
2983             group_by_seq: groupbys || []
2984         }, function (results) {
2985             self.view_list.do_search(results.domain, results.context, results.group_by);
2986         });
2987     },
2988     create_row: function() {
2989         var self = this;
2990         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2991         wdataset.parent_view = this.options.parent_view;
2992         wdataset.child_name = this.options.child_name;
2993         return wdataset.create.apply(wdataset, arguments);
2994     },
2995     write_row: function() {
2996         var self = this;
2997         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2998         wdataset.parent_view = this.options.parent_view;
2999         wdataset.child_name = this.options.child_name;
3000         return wdataset.write.apply(wdataset, arguments);
3001     },
3002     on_select_elements: function(element_ids) {
3003     },
3004     on_click_element: function(ids) {
3005         this.selected_ids = ids || [];
3006         if(this.selected_ids.length > 0) {
3007             this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
3008         } else {
3009             this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
3010         }
3011     },
3012     new_object: function() {
3013         var self = this;
3014         if (this.searchview) {
3015             this.searchview.hide();
3016         }
3017         if (this.view_list) {
3018             this.view_list.$element.hide();
3019         }
3020         this.dataset.index = null;
3021         this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
3022         if (this.options.alternative_form_view) {
3023             this.view_form.set_embedded_view(this.options.alternative_form_view);
3024         }
3025         this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
3026         this.view_form.on_loaded.add_last(function() {
3027             var $buttons = self.view_form.$element.find(".oe_form_buttons");
3028             $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
3029             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
3030             $nbutton.click(function() {
3031                 $.when(self.view_form.do_save()).then(function() {
3032                     self.view_form.reload_mutex.exec(function() {
3033                         self.view_form.on_button_new();
3034                     });
3035                 });
3036             });
3037             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
3038             $nbutton.click(function() {
3039                 $.when(self.view_form.do_save()).then(function() {
3040                     self.view_form.reload_mutex.exec(function() {
3041                         self.check_exit();
3042                     });
3043                 });
3044             });
3045             var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
3046             $cbutton.click(function() {
3047                 self.check_exit();
3048             });
3049         });
3050         this.view_form.do_show();
3051     },
3052     check_exit: function() {
3053         if (this.created_elements.length > 0) {
3054             this.on_select_elements(this.created_elements);
3055         }
3056         this.stop();
3057     },
3058     on_default_get: function(res) {}
3059 });
3060
3061 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
3062     do_add_record: function () {
3063         this.popup.new_object();
3064     },
3065     select_record: function(index) {
3066         this.popup.on_select_elements([this.dataset.ids[index]]);
3067         this.popup.stop();
3068     },
3069     do_select: function(ids, records) {
3070         this._super(ids, records);
3071         this.popup.on_click_element(ids);
3072     }
3073 });
3074
3075 /**
3076  * @class
3077  * @extends openerp.web.OldWidget
3078  */
3079 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
3080     template: "FormOpenPopup",
3081     /**
3082      * options:
3083      * - alternative_form_view
3084      * - auto_write (default true)
3085      * - read_function
3086      * - parent_view
3087      * - child_name
3088      * - form_view_options
3089      * - readonly
3090      */
3091     show_element: function(model, row_id, context, options) {
3092         this.model = model;
3093         this.row_id = row_id;
3094         this.context = context || {};
3095         this.options = _.defaults(options || {}, {"auto_write": true});
3096         this.render_element();
3097         this.$element.dialog({
3098             title: options.title || '',
3099             modal: true,
3100             width: 960,
3101             height: 600
3102         });
3103         this.start();
3104     },
3105     start: function() {
3106         this._super();
3107         this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
3108         this.dataset.fop = this;
3109         this.dataset.ids = [this.row_id];
3110         this.dataset.index = 0;
3111         this.dataset.parent_view = this.options.parent_view;
3112         this.dataset.child_name = this.options.child_name;
3113         this.setup_form_view();
3114     },
3115     on_write: function(id, data) {
3116         if (!this.options.auto_write)
3117             return;
3118         var self = this;
3119         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
3120         wdataset.parent_view = this.options.parent_view;
3121         wdataset.child_name = this.options.child_name;
3122         wdataset.write(id, data, {}, function(r) {
3123             self.on_write_completed();
3124         });
3125     },
3126     on_write_completed: function() {},
3127     setup_form_view: function() {
3128         var self = this;
3129         var FormClass = this.options.readonly
3130                 ? openerp.web.views.get_object('page')
3131                 : openerp.web.views.get_object('form');
3132         this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
3133         if (this.options.alternative_form_view) {
3134             this.view_form.set_embedded_view(this.options.alternative_form_view);
3135         }
3136         this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
3137         this.view_form.on_loaded.add_last(function() {
3138             var $buttons = self.view_form.$element.find(".oe_form_buttons");
3139             $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
3140             var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
3141             $nbutton.click(function() {
3142                 self.view_form.do_save().then(function() {
3143                     self.stop();
3144                 });
3145             });
3146             var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
3147             $cbutton.click(function() {
3148                 self.stop();
3149             });
3150             if (self.options.readonly) {
3151                 $nbutton.hide();
3152                 $cbutton.text(_t("Close"));
3153             }
3154             self.view_form.do_show();
3155         });
3156         this.dataset.on_write.add(this.on_write);
3157     }
3158 });
3159
3160 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
3161     read_ids: function() {
3162         if (this.fop.options.read_function) {
3163             return this.fop.options.read_function.apply(null, arguments);
3164         } else {
3165             return this._super.apply(this, arguments);
3166         }
3167     }
3168 });
3169
3170 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
3171     template: 'FieldReference',
3172     init: function(view, node) {
3173         this._super(view, node);
3174         this.fields_view = {
3175             fields: {
3176                 selection: {
3177                     selection: view.fields_view.fields[this.name].selection
3178                 },
3179                 m2o: {
3180                     relation: null
3181                 }
3182             }
3183         };
3184         this.get_fields_values = view.get_fields_values;
3185         this.get_selected_ids = view.get_selected_ids;
3186         this.do_onchange = this.on_form_changed = this.do_notify_change = this.on_nop;
3187         this.dataset = this.view.dataset;
3188         this.widgets_counter = 0;
3189         this.view_id = 'reference_' + _.uniqueId();
3190         this.widgets = {};
3191         this.fields = {};
3192         this.fields_order = [];
3193         this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
3194             name: 'selection',
3195             widget: 'selection'
3196         }});
3197         this.reference_ready = true;
3198         this.selection.on_value_changed.add_last(this.on_selection_changed);
3199         this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
3200             name: 'm2o',
3201             widget: 'many2one'
3202         }});
3203         this.m2o.on_ui_change.add_last(this.on_ui_change);
3204     },
3205     on_nop: function() {
3206     },
3207     on_selection_changed: function() {
3208         if (this.reference_ready) {
3209             var sel = this.selection.get_value();
3210             this.m2o.field.relation = sel;
3211             this.m2o.set_value(null);
3212             this.m2o.$element.toggle(sel !== false);
3213         }
3214     },
3215     start: function() {
3216         this._super();
3217         this.selection.start();
3218         this.m2o.start();
3219     },
3220     is_valid: function() {
3221         return this.required === false || typeof(this.get_value()) === 'string';
3222     },
3223     is_dirty: function() {
3224         return this.selection.is_dirty() || this.m2o.is_dirty();
3225     },
3226     set_value: function(value) {
3227         this._super(value);
3228         this.reference_ready = false;
3229         var vals = [], sel_val, m2o_val;
3230         if (typeof(value) === 'string') {
3231             vals = value.split(',');
3232         }
3233         sel_val = vals[0] || false;
3234         m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
3235         this.selection.set_value(sel_val);
3236         this.m2o.field.relation = sel_val;
3237         this.m2o.set_value(m2o_val);
3238         this.m2o.$element.toggle(sel_val !== false);
3239         this.reference_ready = true;
3240     },
3241     get_value: function() {
3242         var model = this.selection.get_value(),
3243             id = this.m2o.get_value();
3244         if (typeof(model) === 'string' && typeof(id) === 'number') {
3245             return model + ',' + id;
3246         } else {
3247             return false;
3248         }
3249     }
3250 });
3251
3252 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
3253     init: function(view, node) {
3254         this._super(view, node);
3255         this.iframe = this.element_id + '_iframe';
3256         this.binary_value = false;
3257     },
3258     start: function() {
3259         this._super.apply(this, arguments);
3260         this.$element.find('input.oe-binary-file').change(this.on_file_change);
3261         this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3262         this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3263     },
3264     human_filesize : function(size) {
3265         var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3266         var i = 0;
3267         while (size >= 1024) {
3268             size /= 1024;
3269             ++i;
3270         }
3271         return size.toFixed(2) + ' ' + units[i];
3272     },
3273     on_file_change: function(e) {
3274         // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3275         // http://www.html5rocks.com/tutorials/file/dndfiles/
3276         // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3277         window[this.iframe] = this.on_file_uploaded;
3278         if ($(e.target).val() != '') {
3279             this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3280             this.$element.find('form.oe-binary-form').submit();
3281             this.$element.find('.oe-binary-progress').show();
3282             this.$element.find('.oe-binary').hide();
3283         }
3284     },
3285     on_file_uploaded: function(size, name, content_type, file_base64) {
3286         delete(window[this.iframe]);
3287         if (size === false) {
3288             this.do_warn("File Upload", "There was a problem while uploading your file");
3289             // TODO: use openerp web crashmanager
3290             console.warn("Error while uploading file : ", name);
3291         } else {
3292             this.on_file_uploaded_and_valid.apply(this, arguments);
3293             this.on_ui_change();
3294         }
3295         this.$element.find('.oe-binary-progress').hide();
3296         this.$element.find('.oe-binary').show();
3297     },
3298     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3299     },
3300     on_save_as: function() {
3301         $.blockUI();
3302         this.session.get_file({
3303             url: '/web/binary/saveas_ajax',
3304             data: {data: JSON.stringify({
3305                 model: this.view.dataset.model,
3306                 id: (this.view.datarecord.id || ''),
3307                 field: this.name,
3308                 filename_field: (this.node.attrs.filename || ''),
3309                 context: this.view.dataset.get_context()
3310             })},
3311             complete: $.unblockUI,
3312             error: openerp.webclient.crashmanager.on_rpc_error
3313         });
3314     },
3315     set_filename: function(value) {
3316         var filename = this.node.attrs.filename;
3317         if (this.view.fields[filename]) {
3318             this.view.fields[filename].set_value(value);
3319             this.view.fields[filename].on_ui_change();
3320         }
3321     },
3322     on_clear: function() {
3323         if (this.value !== false) {
3324             this.value = false;
3325             this.binary_value = false;
3326             this.on_ui_change();
3327         }
3328         return false;
3329     }
3330 });
3331
3332 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
3333     template: 'FieldBinaryFile',
3334     update_dom: function() {
3335         this._super.apply(this, arguments);
3336         this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
3337         this.$element.find('input[type=text]').prop('readonly', this.readonly);
3338     },
3339     set_value: function(value) {
3340         this._super.apply(this, arguments);
3341         var show_value;
3342         if (this.node.attrs.filename) {
3343             show_value = this.view.datarecord[this.node.attrs.filename] || '';
3344         } else {
3345             show_value = (value != null && value !== false) ? value : '';
3346         }
3347         this.$element.find('input').eq(0).val(show_value);
3348     },
3349     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3350         this.value = file_base64;
3351         this.binary_value = true;
3352         var show_value = name + " (" + this.human_filesize(size) + ")";
3353         this.$element.find('input').eq(0).val(show_value);
3354         this.set_filename(name);
3355     },
3356     on_clear: function() {
3357         this._super.apply(this, arguments);
3358         this.$element.find('input').eq(0).val('');
3359         this.set_filename('');
3360     }
3361 });
3362
3363 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
3364     template: 'FieldBinaryImage',
3365     start: function() {
3366         this._super.apply(this, arguments);
3367         this.$image = this.$element.find('img.oe-binary-image');
3368     },
3369     update_dom: function() {
3370         this._super.apply(this, arguments);
3371         this.$element.find('.oe-binary').toggle(!this.readonly);
3372     },
3373     set_value: function(value) {
3374         this._super.apply(this, arguments);
3375         this.set_image_maxwidth();
3376         var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
3377             this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
3378         this.$image.attr('src', url);
3379     },
3380     set_image_maxwidth: function() {
3381         this.$image.css('max-width', this.$element.width());
3382     },
3383     on_file_change: function() {
3384         this.set_image_maxwidth();
3385         this._super.apply(this, arguments);
3386     },
3387     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3388         this.value = file_base64;
3389         this.binary_value = true;
3390         this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
3391         this.set_filename(name);
3392     },
3393     on_clear: function() {
3394         this._super.apply(this, arguments);
3395         this.$image.attr('src', '/web/static/src/img/placeholder.png');
3396         this.set_filename('');
3397     }
3398 });
3399
3400 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
3401     template: "EmptyComponent",
3402     start: function() {
3403         this._super();
3404         this.selected_value = null;
3405
3406         this.render_list();
3407     },
3408     set_value: function(value) {
3409         this._super(value);
3410         this.selected_value = value;
3411
3412         this.render_list();
3413     },
3414     render_list: function() {
3415         var self = this;
3416         var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3417             function(x) { return _.str.trim(x); });
3418         shown = _.select(shown, function(x) { return x.length > 0; });
3419
3420         if (shown.length == 0) {
3421             this.to_show = this.field.selection;
3422         } else {
3423             this.to_show = _.select(this.field.selection, function(x) {
3424                 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3425             });
3426         }
3427
3428         var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3429         this.$element.html(content);
3430
3431         var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3432         var color = colors[this.selected_value];
3433         if (color) {
3434             var elem = this.$element.find("li.oe-arrow-list-selected span");
3435             elem.css("border-color", color);
3436             if (this.check_white(color))
3437                 elem.css("color", "white");
3438             elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3439             elem.css("border-left-color", "transparent");
3440             elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3441             elem.css("border-color", "transparent");
3442             elem.css("border-left-color", color);
3443         }
3444     },
3445     check_white: function(color) {
3446         var div = $("<div></div>");
3447         div.css("display", "none");
3448         div.css("color", color);
3449         div.appendTo($("body"));
3450         var ncolor = div.css("color");
3451         div.remove();
3452         var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3453         if (!res) {
3454             return false;
3455         }
3456         var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3457         var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3458         if (lum < 128) {
3459             return true;
3460         }
3461         return false;
3462     }
3463 });
3464
3465 openerp.web.form.WidgetHtml = openerp.web.form.Widget.extend({
3466     render: function () {
3467         var $root = $('<div class="oe_form_html_view">');
3468         this.render_children(this, $root);
3469         return $root.html();
3470     },
3471     render_children: function (object, $into) {
3472         var self = this,
3473             fields = this.view.fields_view.fields;
3474         _(object.children).each(function (child) {
3475             if (typeof child === 'string') {
3476                 $into.text(child);
3477             } else if (child.tag === 'field') {
3478                 $into.append(
3479                     new (self.view.registry.get_object('frame'))(
3480                         self.view, {tag: 'ueule', attrs: {}, children: [child] })
3481                             .render());
3482             } else {
3483                 var $child = $(document.createElement(child.tag))
3484                         .attr(child.attrs)
3485                         .appendTo($into);
3486                 self.render_children(child, $child);
3487             }
3488         });
3489     }
3490 });
3491
3492
3493 /**
3494  * Registry of form widgets, called by :js:`openerp.web.FormView`
3495  */
3496 openerp.web.form.widgets = new openerp.web.Registry({
3497     'frame' : 'openerp.web.form.WidgetFrame',
3498     'group' : 'openerp.web.form.WidgetGroup',
3499     'notebook' : 'openerp.web.form.WidgetNotebook',
3500     'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3501     'separator' : 'openerp.web.form.WidgetSeparator',
3502     'label' : 'openerp.web.form.WidgetLabel',
3503     'button' : 'openerp.web.form.WidgetButton',
3504     'char' : 'openerp.web.form.FieldChar',
3505     'id' : 'openerp.web.form.FieldID',
3506     'email' : 'openerp.web.form.FieldEmail',
3507     'url' : 'openerp.web.form.FieldUrl',
3508     'text' : 'openerp.web.form.FieldText',
3509     'date' : 'openerp.web.form.FieldDate',
3510     'datetime' : 'openerp.web.form.FieldDatetime',
3511     'selection' : 'openerp.web.form.FieldSelection',
3512     'many2one' : 'openerp.web.form.FieldMany2One',
3513     'many2many' : 'openerp.web.form.FieldMany2Many',
3514     'one2many' : 'openerp.web.form.FieldOne2Many',
3515     'one2many_list' : 'openerp.web.form.FieldOne2Many',
3516     'reference' : 'openerp.web.form.FieldReference',
3517     'boolean' : 'openerp.web.form.FieldBoolean',
3518     'float' : 'openerp.web.form.FieldFloat',
3519     'integer': 'openerp.web.form.FieldFloat',
3520     'float_time': 'openerp.web.form.FieldFloat',
3521     'progressbar': 'openerp.web.form.FieldProgressBar',
3522     'image': 'openerp.web.form.FieldBinaryImage',
3523     'binary': 'openerp.web.form.FieldBinaryFile',
3524     'statusbar': 'openerp.web.form.FieldStatus',
3525     'html': 'openerp.web.form.WidgetHtml'
3526 });
3527
3528
3529 };
3530
3531 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: