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