[FIX] error caused by autosave-on-blur when vaidating a row with [Return]
[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                         self.focus();
1968                         return;
1969                     }
1970                     var pop = new openerp.web.form.FormOpenPopup(self.view);
1971                     pop.show_element(
1972                         self.field.relation,
1973                         self.value[0],
1974                         self.build_context(),
1975                         {
1976                             title: _t("Open: ") + (self.string || self.name)
1977                         }
1978                     );
1979                     pop.on_write_completed.add_last(function() {
1980                         self.set_value(self.value[0]);
1981                         self.focus();
1982                     });
1983                 };
1984                 _.each(_.range(self.related_entries.length), function(i) {
1985                     bindings[self.cm_id + "_related_" + i] = function() {
1986                         self.open_related(self.related_entries[i]);
1987                     };
1988                 });
1989                 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'noRightClick': true,
1990                     bindings: bindings, itemStyle: {"color": ""},
1991                     onContextMenu: function() {
1992                         if(self.value) {
1993                             $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1994                         } else {
1995                             $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1996                         }
1997                         if (!self.readonly) {
1998                             $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1999                         } else {
2000                             $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
2001                         }
2002                         return true;
2003                     }, menuStyle: {width: "200px"}
2004                 });
2005                 $.async_when().then(function() {self.$menu_btn.trigger(e);});
2006             });
2007         });
2008         var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
2009         this.$menu_btn.click(ctx_callback);
2010
2011         // some behavior for input
2012         this.$input.keyup(function() {
2013             if (self.$input.val() === "") {
2014                 self._change_int_value(null);
2015             } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
2016                 self._change_int_value(undefined);
2017             }
2018         });
2019         this.$drop_down.click(function() {
2020             if (self.readonly)
2021                 return;
2022             if (self.$input.autocomplete("widget").is(":visible")) {
2023                 self.$input.autocomplete("close");
2024             } else {
2025                 if (self.value) {
2026                     self.$input.autocomplete("search", "");
2027                 } else {
2028                     self.$input.autocomplete("search");
2029                 }
2030             }
2031             self.$input.focus();
2032         });
2033         var anyoneLoosesFocus = function() {
2034             if (!self.$input.is(":focus") &&
2035                     !self.$input.autocomplete("widget").is(":visible") &&
2036                     !self.value) {
2037                 if (self.value === undefined && self.last_search.length > 0) {
2038                     self._change_int_ext_value(self.last_search[0]);
2039                 } else {
2040                     self._change_int_ext_value(null);
2041                 }
2042             }
2043         };
2044         this.$input.focusout(anyoneLoosesFocus);
2045
2046         var isSelecting = false;
2047         // autocomplete
2048         this.$input.autocomplete({
2049             source: function(req, resp) { self.get_search_result(req, resp); },
2050             select: function(event, ui) {
2051                 isSelecting = true;
2052                 var item = ui.item;
2053                 if (item.id) {
2054                     self._change_int_value([item.id, item.name]);
2055                 } else if (item.action) {
2056                     self._change_int_value(undefined);
2057                     item.action();
2058                     return false;
2059                 }
2060             },
2061             focus: function(e, ui) {
2062                 e.preventDefault();
2063             },
2064             html: true,
2065             close: anyoneLoosesFocus,
2066             minLength: 0,
2067             delay: 0
2068         });
2069
2070         // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2071         this.$input.keyup(function(e) {
2072             if (e.which === 13) {
2073                 if (isSelecting)
2074                     e.stopPropagation();
2075             }
2076             isSelecting = false;
2077         });
2078
2079         // avoid triggering blur on the widget when it comes from clicking on
2080         // a completion of the list, on the dropdown or on the m2o menu thing
2081         var picking_completion = false;
2082         this.$input.autocomplete('widget')
2083                 .add(this.$drop_down)
2084                 .add(this.$menu_btn)
2085             .mousedown(function () {
2086                 picking_completion = true;
2087             });
2088         this.$input.add(this.$menu_btn).bind({
2089             blur: function () {
2090                 if (!picking_completion) {
2091                     $(self).trigger('widget-blur');
2092                 }
2093                 picking_completion = false;
2094             },
2095             focus: function () {
2096                 $(self).trigger('widget-focus');
2097             }
2098         })
2099     },
2100     // autocomplete component content handling
2101     get_search_result: function(request, response) {
2102         var search_val = request.term;
2103         var self = this;
2104
2105         if (this.abort_last) {
2106             this.abort_last();
2107             delete this.abort_last;
2108         }
2109         var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2110
2111         dataset.name_search(search_val, self.build_domain(), 'ilike',
2112                 this.limit + 1, function(data) {
2113             self.last_search = data;
2114             // possible selections for the m2o
2115             var values = _.map(data, function(x) {
2116                 return {
2117                     label: _.str.escapeHTML(x[1]),
2118                     value:x[1],
2119                     name:x[1],
2120                     id:x[0]
2121                 };
2122             });
2123
2124             // search more... if more results that max
2125             if (values.length > self.limit) {
2126                 var open_search_popup = function(data) {
2127                     self._change_int_value(null);
2128                     self._search_create_popup("search", data);
2129                 };
2130                 values = values.slice(0, self.limit);
2131                 values.push({label: _t("<em>   Search More...</em>"), action: function() {
2132                     if (!search_val) {
2133                         // search optimisation - in case user didn't enter any text we
2134                         // do not need to prefilter records; for big datasets (ex: more
2135                         // that 10.000 records) calling name_search() could be very very
2136                         // expensive!
2137                         open_search_popup();
2138                         return;
2139                     }
2140                     dataset.name_search(search_val, self.build_domain(),
2141                                         'ilike', false, open_search_popup);
2142                 }});
2143             }
2144             // quick create
2145             var raw_result = _(data.result).map(function(x) {return x[1];});
2146             if (search_val.length > 0 &&
2147                 !_.include(raw_result, search_val) &&
2148                 (!self.value || search_val !== self.value[1])) {
2149                 values.push({label: _.str.sprintf(_t('<em>   Create "<strong>%s</strong>"</em>'),
2150                         $('<span />').text(search_val).html()), action: function() {
2151                     self._quick_create(search_val);
2152                 }});
2153             }
2154             // create...
2155             values.push({label: _t("<em>   Create and Edit...</em>"), action: function() {
2156                 self._change_int_value(null);
2157                 self._search_create_popup("form", undefined, {"default_name": search_val});
2158             }});
2159
2160             response(values);
2161         });
2162         this.abort_last = dataset.abort_last;
2163     },
2164     _quick_create: function(name) {
2165         var self = this;
2166         var slow_create = function () {
2167             self._change_int_value(null);
2168             self._search_create_popup("form", undefined, {"default_name": name});
2169         };
2170         if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2171             var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2172             dataset.name_create(name, function(data) {
2173                 self._change_int_ext_value(data);
2174             }).fail(function(error, event) {
2175                 event.preventDefault();
2176                 slow_create();
2177             });
2178         } else
2179             slow_create();
2180     },
2181     // all search/create popup handling
2182     _search_create_popup: function(view, ids, context) {
2183         var self = this;
2184         var pop = new openerp.web.form.SelectCreatePopup(this);
2185         pop.select_element(
2186             self.field.relation,
2187             {
2188                 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2189                 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2190                 initial_view: view,
2191                 disable_multiple_selection: true
2192             },
2193             self.build_domain(),
2194             new openerp.web.CompoundContext(self.build_context(), context || {})
2195         );
2196         pop.on_select_elements.add(function(element_ids) {
2197             var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
2198             dataset.name_get([element_ids[0]], function(data) {
2199                 self._change_int_ext_value(data[0]);
2200                 self.focus();
2201             });
2202         });
2203     },
2204     _change_int_ext_value: function(value) {
2205         this._change_int_value(value);
2206         this.$input.val(this.value ? this.value[1] : "");
2207     },
2208     _change_int_value: function(value) {
2209         this.value = value;
2210         var back_orig_value = this.original_value;
2211         if (this.value === null || this.value) {
2212             this.original_value = this.value;
2213         }
2214         if (back_orig_value === undefined) { // first use after a set_value()
2215             return;
2216         }
2217         if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
2218                 !== (this.value ? this.value[0] : null))) {
2219             this.on_ui_change();
2220         }
2221     },
2222     set_value: function(value) {
2223         value = value || null;
2224         this.invalid = false;
2225         var self = this;
2226         this.tmp_value = value;
2227         self.update_dom();
2228         self.on_value_changed();
2229         var real_set_value = function(rval) {
2230             self.tmp_value = undefined;
2231             self.value = rval;
2232             self.original_value = undefined;
2233             self._change_int_ext_value(rval);
2234         };
2235         if (value && !(value instanceof Array)) {
2236             // name_get in a m2o does not use the context of the field
2237             var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2238             dataset.name_get([value], function(data) {
2239                 real_set_value(data[0]);
2240             }).fail(function() {self.tmp_value = undefined;});
2241         } else {
2242             $.async_when().then(function() {real_set_value(value);});
2243         }
2244     },
2245     get_value: function() {
2246         if (this.tmp_value !== undefined) {
2247             if (this.tmp_value instanceof Array) {
2248                 return this.tmp_value[0];
2249             }
2250             return this.tmp_value ? this.tmp_value : false;
2251         }
2252         if (this.value === undefined)
2253             return this.original_value ? this.original_value[0] : false;
2254         return this.value ? this.value[0] : false;
2255     },
2256     validate: function() {
2257         this.invalid = false;
2258         var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
2259         if (val === null) {
2260             this.invalid = this.required;
2261         }
2262     },
2263     open_related: function(related) {
2264         var self = this;
2265         if (!self.value)
2266             return;
2267         var additional_context = {
2268                 active_id: self.value[0],
2269                 active_ids: [self.value[0]],
2270                 active_model: self.field.relation
2271         };
2272         self.rpc("/web/action/load", {
2273             action_id: related[2].id,
2274             context: additional_context
2275         }, function(result) {
2276             result.result.context = _.extend(result.result.context || {}, additional_context);
2277             self.do_action(result.result);
2278         });
2279     },
2280     focus: function ($element) {
2281         this._super($element || this.$input);
2282     },
2283     update_dom: function() {
2284         this._super.apply(this, arguments);
2285         this.$input.prop('readonly', this.readonly);
2286     }
2287 });
2288
2289 /*
2290 # Values: (0, 0,  { fields })    create
2291 #         (1, ID, { fields })    update
2292 #         (2, ID)                remove (delete)
2293 #         (3, ID)                unlink one (target id or target of relation)
2294 #         (4, ID)                link
2295 #         (5)                    unlink all (only valid for one2many)
2296 */
2297 var commands = {
2298     // (0, _, {values})
2299     CREATE: 0,
2300     'create': function (values) {
2301         return [commands.CREATE, false, values];
2302     },
2303     // (1, id, {values})
2304     UPDATE: 1,
2305     'update': function (id, values) {
2306         return [commands.UPDATE, id, values];
2307     },
2308     // (2, id[, _])
2309     DELETE: 2,
2310     'delete': function (id) {
2311         return [commands.DELETE, id, false];
2312     },
2313     // (3, id[, _]) removes relation, but not linked record itself
2314     FORGET: 3,
2315     'forget': function (id) {
2316         return [commands.FORGET, id, false];
2317     },
2318     // (4, id[, _])
2319     LINK_TO: 4,
2320     'link_to': function (id) {
2321         return [commands.LINK_TO, id, false];
2322     },
2323     // (5[, _[, _]])
2324     DELETE_ALL: 5,
2325     'delete_all': function () {
2326         return [5, false, false];
2327     },
2328     // (6, _, ids) replaces all linked records with provided ids
2329     REPLACE_WITH: 6,
2330     'replace_with': function (ids) {
2331         return [6, false, ids];
2332     }
2333 };
2334 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2335     template: 'FieldOne2Many',
2336     multi_selection: false,
2337     init: function(view, node) {
2338         this._super(view, node);
2339         this.is_loaded = $.Deferred();
2340         this.initial_is_loaded = this.is_loaded;
2341         this.is_setted = $.Deferred();
2342         this.form_last_update = $.Deferred();
2343         this.init_form_last_update = this.form_last_update;
2344         this.disable_utility_classes = true;
2345     },
2346     start: function() {
2347         this._super.apply(this, arguments);
2348
2349         var self = this;
2350
2351         this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2352         this.dataset.o2m = this;
2353         this.dataset.parent_view = this.view;
2354         this.dataset.child_name = this.name;
2355         //this.dataset.child_name = 
2356         this.dataset.on_change.add_last(function() {
2357             self.trigger_on_change();
2358         });
2359
2360         this.is_setted.then(function() {
2361             self.load_views();
2362         });
2363     },
2364     trigger_on_change: function() {
2365         var tmp = this.doing_on_change;
2366         this.doing_on_change = true;
2367         this.on_ui_change();
2368         this.doing_on_change = tmp;
2369     },
2370     is_readonly: function() {
2371         return this.readonly || this.force_readonly;
2372     },
2373     load_views: function() {
2374         var self = this;
2375         
2376         var modes = this.node.attrs.mode;
2377         modes = !!modes ? modes.split(",") : ["tree"];
2378         var views = [];
2379         _.each(modes, function(mode) {
2380             var view = {
2381                 view_id: false,
2382                 view_type: mode == "tree" ? "list" : mode,
2383                 options: { sidebar : false }
2384             };
2385             if (self.field.views && self.field.views[mode]) {
2386                 view.embedded_view = self.field.views[mode];
2387             }
2388             if(view.view_type === "list") {
2389                 view.options.selectable = self.multi_selection;
2390                 if (self.is_readonly()) {
2391                     view.options.addable = null;
2392                     view.options.deletable = null;
2393                     view.options.isClarkGable = false;
2394                 }
2395             } else if (view.view_type === "form") {
2396                 if (self.is_readonly()) {
2397                     view.view_type = 'page';
2398                 }
2399                 view.options.not_interactible_on_create = true;
2400             }
2401             views.push(view);
2402         });
2403         this.views = views;
2404
2405         this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views, {});
2406         this.viewmanager.template = 'One2Many.viewmanager';
2407         this.viewmanager.registry = openerp.web.views.extend({
2408             list: 'openerp.web.form.One2ManyListView',
2409             form: 'openerp.web.form.One2ManyFormView',
2410             page: 'openerp.web.PageView'
2411         });
2412         var once = $.Deferred().then(function() {
2413             self.init_form_last_update.resolve();
2414         });
2415         var def = $.Deferred().then(function() {
2416             self.initial_is_loaded.resolve();
2417         });
2418         this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2419             if (view_type == "list") {
2420                 controller.o2m = self;
2421                 if (self.is_readonly())
2422                     controller.set_editable(false);
2423             } else if (view_type == "form" || view_type == 'page') {
2424                 if (view_type == 'page' || self.is_readonly()) {
2425                     $(".oe_form_buttons", controller.$element).children().remove();
2426                 }
2427                 controller.on_record_loaded.add_last(function() {
2428                     once.resolve();
2429                 });
2430                 controller.on_pager_action.add_first(function() {
2431                     self.save_any_view();
2432                 });
2433             } else if (view_type == "graph") {
2434                 self.reload_current_view()
2435             }
2436             def.resolve();
2437         });
2438         this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2439             $.when(self.save_any_view()).then(function() {
2440                 if(n_mode === "list")
2441                     $.async_when().then(function() {self.reload_current_view();});
2442             });
2443         });
2444         this.is_setted.then(function() {
2445             $.async_when().then(function () {
2446                 self.viewmanager.appendTo(self.$element);
2447             });
2448         });
2449         return def;
2450     },
2451     reload_current_view: function() {
2452         var self = this;
2453         return self.is_loaded = self.is_loaded.pipe(function() {
2454             var active_view = self.viewmanager.active_view;
2455             var view = self.viewmanager.views[active_view].controller;
2456             if(active_view === "list") {
2457                 return view.reload_content();
2458             } else if (active_view === "form" || active_view === 'page') {
2459                 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2460                     self.dataset.index = 0;
2461                 }
2462                 var act = function() {
2463                     return view.do_show();
2464                 };
2465                 self.form_last_update = self.form_last_update.pipe(act, act);
2466                 return self.form_last_update;
2467             } else if (active_view === "graph") {
2468                 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2469             }
2470         }, undefined);
2471     },
2472     set_value: function(value) {
2473         value = value || [];
2474         var self = this;
2475         this.dataset.reset_ids([]);
2476         if(value.length >= 1 && value[0] instanceof Array) {
2477             var ids = [];
2478             _.each(value, function(command) {
2479                 var obj = {values: command[2]};
2480                 switch (command[0]) {
2481                     case commands.CREATE:
2482                         obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2483                         obj.defaults = {};
2484                         self.dataset.to_create.push(obj);
2485                         self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2486                         ids.push(obj.id);
2487                         return;
2488                     case commands.UPDATE:
2489                         obj['id'] = command[1];
2490                         self.dataset.to_write.push(obj);
2491                         self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2492                         ids.push(obj.id);
2493                         return;
2494                     case commands.DELETE:
2495                         self.dataset.to_delete.push({id: command[1]});
2496                         return;
2497                     case commands.LINK_TO:
2498                         ids.push(command[1]);
2499                         return;
2500                     case commands.DELETE_ALL:
2501                         self.dataset.delete_all = true;
2502                         return;
2503                 }
2504             });
2505             this._super(ids);
2506             this.dataset.set_ids(ids);
2507         } else if (value.length >= 1 && typeof(value[0]) === "object") {
2508             var ids = [];
2509             this.dataset.delete_all = true;
2510             _.each(value, function(command) {
2511                 var obj = {values: command};
2512                 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2513                 obj.defaults = {};
2514                 self.dataset.to_create.push(obj);
2515                 self.dataset.cache.push(_.clone(obj));
2516                 ids.push(obj.id);
2517             });
2518             this._super(ids);
2519             this.dataset.set_ids(ids);
2520         } else {
2521             this._super(value);
2522             this.dataset.reset_ids(value);
2523         }
2524         if (this.dataset.index === null && this.dataset.ids.length > 0) {
2525             this.dataset.index = 0;
2526         }
2527         self.is_setted.resolve();
2528         return self.reload_current_view();
2529     },
2530     get_value: function() {
2531         var self = this;
2532         if (!this.dataset)
2533             return [];
2534         this.save_any_view();
2535         var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2536         val = val.concat(_.map(this.dataset.ids, function(id) {
2537             var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2538             if (alter_order) {
2539                 return commands.create(alter_order.values);
2540             }
2541             alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2542             if (alter_order) {
2543                 return commands.update(alter_order.id, alter_order.values);
2544             }
2545             return commands.link_to(id);
2546         }));
2547         return val.concat(_.map(
2548             this.dataset.to_delete, function(x) {
2549                 return commands['delete'](x.id);}));
2550     },
2551     save_any_view: function() {
2552         if (this.doing_on_change)
2553             return false;
2554         return this.session.synchronized_mode(_.bind(function() {
2555                 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2556                     this.viewmanager.views[this.viewmanager.active_view] &&
2557                     this.viewmanager.views[this.viewmanager.active_view].controller) {
2558                     var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2559                     if (this.viewmanager.active_view === "form") {
2560                         if (!view.is_initialized.isResolved()) {
2561                             return false;
2562                         }
2563                         var res = $.when(view.do_save());
2564                         if (!res.isResolved() && !res.isRejected()) {
2565                             console.warn("Asynchronous get_value() is not supported in form view.");
2566                         }
2567                         return res;
2568                     } else if (this.viewmanager.active_view === "list") {
2569                         var res = $.when(view.ensure_saved());
2570                         if (!res.isResolved() && !res.isRejected()) {
2571                             console.warn("Asynchronous get_value() is not supported in list view.");
2572                         }
2573                         return res;
2574                     }
2575                 }
2576                 return false;
2577             }, this));
2578     },
2579     is_valid: function() {
2580         if (!this.viewmanager.views[this.viewmanager.active_view])
2581             return true;
2582         var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2583         switch (this.viewmanager.active_view) {
2584         case 'form':
2585             return _(view.fields).chain()
2586                 .invoke('is_valid')
2587                 .all(_.identity)
2588                 .value();
2589             break;
2590         case 'list':
2591             return view.is_valid();
2592         }
2593         return true;
2594     },
2595     is_dirty: function() {
2596         this.save_any_view();
2597         return this._super();
2598     },
2599     update_dom: function() {
2600         this._super.apply(this, arguments);
2601         var self = this;
2602         if (this.previous_readonly !== this.readonly) {
2603             this.previous_readonly = this.readonly;
2604             if (this.viewmanager) {
2605                 this.is_loaded = this.is_loaded.pipe(function() {
2606                     self.viewmanager.stop();
2607                     return $.when(self.load_views()).then(function() {
2608                         self.reload_current_view();
2609                     });
2610                 });
2611             }
2612         }
2613     }
2614 });
2615
2616 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2617     get_context: function() {
2618         this.context = this.o2m.build_context([this.o2m.name]);
2619         return this.context;
2620     }
2621 });
2622
2623 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2624     _template: 'One2Many.listview',
2625     init: function (parent, dataset, view_id, options) {
2626         this._super(parent, dataset, view_id, _.extend(options || {}, {
2627             ListType: openerp.web.form.One2ManyList
2628         }));
2629     },
2630     is_valid: function () {
2631         var form;
2632         // A list not being edited is always valid
2633         if (!(form = this.first_edition_form())) {
2634             return true;
2635         }
2636         // If the form has not been modified, the view can only be valid
2637         // NB: is_dirty will also be set on defaults/onchanges/whatever?
2638         // oe_form_dirty seems to only be set on actual user actions
2639         if (!form.$element.is('.oe_form_dirty')) {
2640             return true;
2641         }
2642
2643         // Otherwise validate internal form
2644         return _(form.fields).chain()
2645             .invoke(function () {
2646                 this.validate();
2647                 this.update_dom(true);
2648                 return this.is_valid();
2649             })
2650             .all(_.identity)
2651             .value();
2652     },
2653     first_edition_form: function () {
2654         var get_form = function (group_or_list) {
2655             if (group_or_list.edition) {
2656                 return group_or_list.edition_form;
2657             }
2658             return _(group_or_list.children).chain()
2659                 .map(get_form)
2660                 .compact()
2661                 .first()
2662                 .value();
2663         };
2664         return get_form(this.groups);
2665     },
2666     do_add_record: function () {
2667         if (this.options.editable) {
2668             this._super.apply(this, arguments);
2669         } else {
2670             var self = this;
2671             var pop = new openerp.web.form.SelectCreatePopup(this);
2672             pop.on_default_get.add(self.dataset.on_default_get);
2673             pop.select_element(
2674                 self.o2m.field.relation,
2675                 {
2676                     title: _t("Create: ") + self.name,
2677                     initial_view: "form",
2678                     alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2679                     create_function: function(data, callback, error_callback) {
2680                         return self.o2m.dataset.create(data).then(function(r) {
2681                             self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2682                             self.o2m.dataset.on_change();
2683                         }).then(callback, error_callback);
2684                     },
2685                     read_function: function() {
2686                         return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2687                     },
2688                     parent_view: self.o2m.view,
2689                     child_name: self.o2m.name,
2690                     form_view_options: {'not_interactible_on_create':true}
2691                 },
2692                 self.o2m.build_domain(),
2693                 self.o2m.build_context()
2694             );
2695             pop.on_select_elements.add_last(function() {
2696                 self.o2m.reload_current_view();
2697             });
2698         }
2699     },
2700     do_activate_record: function(index, id) {
2701         var self = this;
2702         var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2703         pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2704             title: _t("Open: ") + self.name,
2705             auto_write: false,
2706             alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2707             parent_view: self.o2m.view,
2708             child_name: self.o2m.name,
2709             read_function: function() {
2710                 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2711             },
2712             form_view_options: {'not_interactible_on_create':true},
2713             readonly: self.o2m.is_readonly()
2714         });
2715         pop.dataset.call_button = function() {
2716             var button_result = self.o2m.dataset.call_button.apply(self.o2m.dataset, arguments);
2717             self.o2m.reload_current_view();
2718             return button_result;
2719         };
2720         pop.on_write.add(function(id, data) {
2721             self.o2m.dataset.write(id, data, {}, function(r) {
2722                 self.o2m.reload_current_view();
2723             });
2724         });
2725     },
2726     do_button_action: function (name, id, callback) {
2727         var self = this;
2728         var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
2729         return this._super(name, id, _.bind(def.resolve, def));
2730     }
2731 });
2732 openerp.web.form.One2ManyList = openerp.web.ListView.List.extend({
2733     KEY_RETURN: 13,
2734     // blurring caused by hitting the [Return] key, should skip the
2735     // autosave-on-blur and let the handler for [Return] do its thing
2736     __return_blur: false,
2737     render_row_as_form: function () {
2738         var self = this;
2739         return this._super.apply(this, arguments).then(function () {
2740             $(self.edition_form).bind('form-blur', function () {
2741                 if (self.__return_blur) {
2742                     delete self.__return_blur;
2743                     return;
2744                 }
2745                 if (!self.edition_form.widget_is_stopped) {
2746                     self.view.ensure_saved();
2747                 }
2748             });
2749         });
2750     },
2751     on_row_keyup: function (e) {
2752         if (e.which === this.KEY_RETURN) {
2753             this.__return_blur = true;
2754         }
2755         this._super(e);
2756     }
2757 });
2758
2759 openerp.web.form.One2ManyFormView = openerp.web.FormView.extend({
2760     form_template: 'One2Many.formview',
2761     on_loaded: function(data) {
2762         this._super(data);
2763         var self = this;
2764         this.$form_header.find('button.oe_form_button_create').click(function() {
2765             self.do_save().then(self.on_button_new);
2766         });
2767     },
2768     do_notify_change: function() {
2769         if (this.dataset.parent_view) {
2770             this.dataset.parent_view.do_notify_change();
2771         } else {
2772             this._super.apply(this, arguments);
2773         }
2774     }
2775 });
2776
2777 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2778     template: 'FieldMany2Many',
2779     multi_selection: false,
2780     init: function(view, node) {
2781         this._super(view, node);
2782         this.list_id = _.uniqueId("many2many");
2783         this.is_loaded = $.Deferred();
2784         this.initial_is_loaded = this.is_loaded;
2785         this.is_setted = $.Deferred();
2786     },
2787     start: function() {
2788         this._super.apply(this, arguments);
2789
2790         var self = this;
2791
2792         this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2793         this.dataset.m2m = this;
2794         this.dataset.on_unlink.add_last(function(ids) {
2795             self.on_ui_change();
2796         });
2797         
2798         this.is_setted.then(function() {
2799             self.load_view();
2800         });
2801     },
2802     set_value: function(value) {
2803         value = value || [];
2804         if (value.length >= 1 && value[0] instanceof Array) {
2805             value = value[0][2];
2806         }
2807         this._super(value);
2808         this.dataset.set_ids(value);
2809         var self = this;
2810         self.reload_content();
2811         this.is_setted.resolve();
2812     },
2813     get_value: function() {
2814         return [commands.replace_with(this.dataset.ids)];
2815     },
2816     validate: function() {
2817         this.invalid = this.required && _(this.dataset.ids).isEmpty();
2818     },
2819     is_readonly: function() {
2820         return this.readonly || this.force_readonly;
2821     },
2822     load_view: function() {
2823         var self = this;
2824         this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2825                     'addable': self.is_readonly() ? null : _t("Add"),
2826                     'deletable': self.is_readonly() ? false : true,
2827                     'selectable': self.multi_selection,
2828                     'isClarkGable': self.is_readonly() ? false : true
2829             });
2830         var embedded = (this.field.views || {}).tree;
2831         if (embedded) {
2832             this.list_view.set_embedded_view(embedded);
2833         }
2834         this.list_view.m2m_field = this;
2835         var loaded = $.Deferred();
2836         this.list_view.on_loaded.add_last(function() {
2837             self.initial_is_loaded.resolve();
2838             loaded.resolve();
2839         });
2840         $.async_when().then(function () {
2841             self.list_view.appendTo($("#" + self.list_id));
2842         });
2843         return loaded;
2844     },
2845     reload_content: function() {
2846         var self = this;
2847         this.is_loaded = this.is_loaded.pipe(function() {
2848             return self.list_view.reload_content();
2849         });
2850     },
2851     update_dom: function() {
2852         this._super.apply(this, arguments);
2853         var self = this;
2854         if (this.previous_readonly !== this.readonly) {
2855             this.previous_readonly = this.readonly;
2856             if (this.list_view) {
2857                 this.is_loaded = this.is_loaded.pipe(function() {
2858                     self.list_view.stop();
2859                     return $.when(self.load_view()).then(function() {
2860                         self.reload_content();
2861                     });
2862                 });
2863             }
2864         }
2865     }
2866 });
2867
2868 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2869     get_context: function() {
2870         this.context = this.m2m.build_context();
2871         return this.context;
2872     }
2873 });
2874
2875 /**
2876  * @class
2877  * @extends openerp.web.ListView
2878  */
2879 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2880     do_add_record: function () {
2881         var pop = new openerp.web.form.SelectCreatePopup(this);
2882         pop.select_element(
2883             this.model,
2884             {
2885                 title: _t("Add: ") + this.name
2886             },
2887             new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2888             this.m2m_field.build_context()
2889         );
2890         var self = this;
2891         pop.on_select_elements.add(function(element_ids) {
2892             _.each(element_ids, function(element_id) {
2893                 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2894                     self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2895                     self.m2m_field.on_ui_change();
2896                     self.reload_content();
2897                 }
2898             });
2899         });
2900     },
2901     do_activate_record: function(index, id) {
2902         var self = this;
2903         var pop = new openerp.web.form.FormOpenPopup(this);
2904         pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
2905             title: _t("Open: ") + this.name,
2906             readonly: this.widget_parent.is_readonly()
2907         });
2908         pop.on_write_completed.add_last(function() {
2909             self.reload_content();
2910         });
2911     }
2912 });
2913
2914 /**
2915  * @class
2916  * @extends openerp.web.OldWidget
2917  */
2918 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2919     template: "SelectCreatePopup",
2920     /**
2921      * options:
2922      * - initial_ids
2923      * - initial_view: form or search (default search)
2924      * - disable_multiple_selection
2925      * - alternative_form_view
2926      * - create_function (defaults to a naive saving behavior)
2927      * - parent_view
2928      * - child_name
2929      * - form_view_options
2930      * - list_view_options
2931      * - read_function
2932      */
2933     select_element: function(model, options, domain, context) {
2934         var self = this;
2935         this.model = model;
2936         this.domain = domain || [];
2937         this.context = context || {};
2938         this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2939             return self.create_row.apply(self, arguments);
2940         }, read_function: null});
2941         this.initial_ids = this.options.initial_ids;
2942         this.created_elements = [];
2943         this.render_element();
2944         openerp.web.form.dialog(this.$element, {
2945             close: function() {
2946                 self.check_exit();
2947             },
2948             title: options.title || ""
2949         });
2950         this.start();
2951     },
2952     start: function() {
2953         this._super();
2954         var self = this;
2955         this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2956             this.context);
2957         this.dataset.create_function = function() {
2958             return self.options.create_function.apply(null, arguments).then(function(r) {
2959                 self.created_elements.push(r.result);
2960             });
2961         };
2962         this.dataset.write_function = function() {
2963             return self.write_row.apply(self, arguments);
2964         };
2965         this.dataset.read_function = this.options.read_function;
2966         this.dataset.parent_view = this.options.parent_view;
2967         this.dataset.child_name = this.options.child_name;
2968         this.dataset.on_default_get.add(this.on_default_get);
2969         if (this.options.initial_view == "search") {
2970             self.rpc('/web/session/eval_domain_and_context', {
2971                 domains: [],
2972                 contexts: [this.context]
2973             }, function (results) {
2974                 var search_defaults = {};
2975                 _.each(results.context, function (value, key) {
2976                     var match = /^search_default_(.*)$/.exec(key);
2977                     if (match) {
2978                         search_defaults[match[1]] = value;
2979                     }
2980                 });
2981                 self.setup_search_view(search_defaults);
2982             });
2983         } else { // "form"
2984             this.new_object();
2985         }
2986     },
2987     stop: function () {
2988         this.$element.dialog('close');
2989         this._super();
2990     },
2991     setup_search_view: function(search_defaults) {
2992         var self = this;
2993         if (this.searchview) {
2994             this.searchview.stop();
2995         }
2996         this.searchview = new openerp.web.SearchView(this,
2997                 this.dataset, false,  search_defaults);
2998         this.searchview.on_search.add(function(domains, contexts, groupbys) {
2999             if (self.initial_ids) {
3000                 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
3001                     contexts, groupbys);
3002                 self.initial_ids = undefined;
3003             } else {
3004                 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
3005             }
3006         });
3007         this.searchview.on_loaded.add_last(function () {
3008             self.view_list = new openerp.web.form.SelectCreateListView(self,
3009                     self.dataset, false,
3010                     _.extend({'deletable': false,
3011                         'selectable': !self.options.disable_multiple_selection
3012                     }, self.options.list_view_options || {}));
3013             self.view_list.popup = self;
3014             self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
3015                 self.view_list.do_show();
3016             }).pipe(function() {
3017                 self.searchview.do_search();
3018             });
3019             self.view_list.on_loaded.add_last(function() {
3020                 var $buttons = self.view_list.$element.find(".oe-actions");
3021                 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
3022                 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
3023                 $cbutton.click(function() {
3024                     self.stop();
3025                 });
3026                 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
3027                 if(self.options.disable_multiple_selection) {
3028                     $sbutton.hide();
3029                 }
3030                 $sbutton.click(function() {
3031                     self.on_select_elements(self.selected_ids);
3032                     self.stop();
3033                 });
3034             });
3035         });
3036         this.searchview.appendTo($("#" + this.element_id + "_search"));
3037     },
3038     do_search: function(domains, contexts, groupbys) {
3039         var self = this;
3040         this.rpc('/web/session/eval_domain_and_context', {
3041             domains: domains || [],
3042             contexts: contexts || [],
3043             group_by_seq: groupbys || []
3044         }, function (results) {
3045             self.view_list.do_search(results.domain, results.context, results.group_by);
3046         });
3047     },
3048     create_row: function() {
3049         var self = this;
3050         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
3051         wdataset.parent_view = this.options.parent_view;
3052         wdataset.child_name = this.options.child_name;
3053         return wdataset.create.apply(wdataset, arguments);
3054     },
3055     write_row: function() {
3056         var self = this;
3057         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
3058         wdataset.parent_view = this.options.parent_view;
3059         wdataset.child_name = this.options.child_name;
3060         return wdataset.write.apply(wdataset, arguments);
3061     },
3062     on_select_elements: function(element_ids) {
3063     },
3064     on_click_element: function(ids) {
3065         this.selected_ids = ids || [];
3066         if(this.selected_ids.length > 0) {
3067             this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
3068         } else {
3069             this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
3070         }
3071     },
3072     new_object: function() {
3073         var self = this;
3074         if (this.searchview) {
3075             this.searchview.hide();
3076         }
3077         if (this.view_list) {
3078             this.view_list.$element.hide();
3079         }
3080         this.dataset.index = null;
3081         this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
3082         if (this.options.alternative_form_view) {
3083             this.view_form.set_embedded_view(this.options.alternative_form_view);
3084         }
3085         this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
3086         this.view_form.on_loaded.add_last(function() {
3087             var $buttons = self.view_form.$element.find(".oe_form_buttons");
3088             $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
3089             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
3090             $nbutton.click(function() {
3091                 $.when(self.view_form.do_save()).then(function() {
3092                     self.view_form.reload_mutex.exec(function() {
3093                         self.view_form.on_button_new();
3094                     });
3095                 });
3096             });
3097             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
3098             $nbutton.click(function() {
3099                 $.when(self.view_form.do_save()).then(function() {
3100                     self.view_form.reload_mutex.exec(function() {
3101                         self.check_exit();
3102                     });
3103                 });
3104             });
3105             var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
3106             $cbutton.click(function() {
3107                 self.check_exit();
3108             });
3109         });
3110         this.view_form.do_show();
3111     },
3112     check_exit: function() {
3113         if (this.created_elements.length > 0) {
3114             this.on_select_elements(this.created_elements);
3115         }
3116         this.stop();
3117     },
3118     on_default_get: function(res) {}
3119 });
3120
3121 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
3122     do_add_record: function () {
3123         this.popup.new_object();
3124     },
3125     select_record: function(index) {
3126         this.popup.on_select_elements([this.dataset.ids[index]]);
3127         this.popup.stop();
3128     },
3129     do_select: function(ids, records) {
3130         this._super(ids, records);
3131         this.popup.on_click_element(ids);
3132     }
3133 });
3134
3135 /**
3136  * @class
3137  * @extends openerp.web.OldWidget
3138  */
3139 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
3140     template: "FormOpenPopup",
3141     /**
3142      * options:
3143      * - alternative_form_view
3144      * - auto_write (default true)
3145      * - read_function
3146      * - parent_view
3147      * - child_name
3148      * - form_view_options
3149      * - readonly
3150      */
3151     show_element: function(model, row_id, context, options) {
3152         this.model = model;
3153         this.row_id = row_id;
3154         this.context = context || {};
3155         this.options = _.defaults(options || {}, {"auto_write": true});
3156         this.render_element();
3157         this.$element.dialog({
3158             title: options.title || '',
3159             modal: true,
3160             width: 960,
3161             height: 600
3162         });
3163         this.start();
3164     },
3165     start: function() {
3166         this._super();
3167         this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
3168         this.dataset.fop = this;
3169         this.dataset.ids = [this.row_id];
3170         this.dataset.index = 0;
3171         this.dataset.parent_view = this.options.parent_view;
3172         this.dataset.child_name = this.options.child_name;
3173         this.setup_form_view();
3174     },
3175     on_write: function(id, data) {
3176         if (!this.options.auto_write)
3177             return;
3178         var self = this;
3179         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
3180         wdataset.parent_view = this.options.parent_view;
3181         wdataset.child_name = this.options.child_name;
3182         wdataset.write(id, data, {}, function(r) {
3183             self.on_write_completed();
3184         });
3185     },
3186     on_write_completed: function() {},
3187     setup_form_view: function() {
3188         var self = this;
3189         var FormClass = this.options.readonly
3190                 ? openerp.web.views.get_object('page')
3191                 : openerp.web.views.get_object('form');
3192         this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
3193         if (this.options.alternative_form_view) {
3194             this.view_form.set_embedded_view(this.options.alternative_form_view);
3195         }
3196         this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
3197         this.view_form.on_loaded.add_last(function() {
3198             var $buttons = self.view_form.$element.find(".oe_form_buttons");
3199             $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
3200             var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
3201             $nbutton.click(function() {
3202                 self.view_form.do_save().then(function() {
3203                     self.stop();
3204                 });
3205             });
3206             var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
3207             $cbutton.click(function() {
3208                 self.stop();
3209             });
3210             if (self.options.readonly) {
3211                 $nbutton.hide();
3212                 $cbutton.text(_t("Close"));
3213             }
3214             self.view_form.do_show();
3215         });
3216         this.dataset.on_write.add(this.on_write);
3217     }
3218 });
3219
3220 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
3221     read_ids: function() {
3222         if (this.fop.options.read_function) {
3223             return this.fop.options.read_function.apply(null, arguments);
3224         } else {
3225             return this._super.apply(this, arguments);
3226         }
3227     }
3228 });
3229
3230 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
3231     template: 'FieldReference',
3232     init: function(view, node) {
3233         this._super(view, node);
3234         this.fields_view = {
3235             fields: {
3236                 selection: {
3237                     selection: view.fields_view.fields[this.name].selection
3238                 },
3239                 m2o: {
3240                     relation: null
3241                 }
3242             }
3243         };
3244         this.get_fields_values = view.get_fields_values;
3245         this.get_selected_ids = view.get_selected_ids;
3246         this.do_onchange = this.on_form_changed = this.do_notify_change = this.on_nop;
3247         this.dataset = this.view.dataset;
3248         this.widgets_counter = 0;
3249         this.view_id = 'reference_' + _.uniqueId();
3250         this.widgets = {};
3251         this.fields = {};
3252         this.fields_order = [];
3253         this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
3254             name: 'selection',
3255             widget: 'selection'
3256         }});
3257         this.reference_ready = true;
3258         this.selection.on_value_changed.add_last(this.on_selection_changed);
3259         this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
3260             name: 'm2o',
3261             widget: 'many2one'
3262         }});
3263         this.m2o.on_ui_change.add_last(this.on_ui_change);
3264     },
3265     on_nop: function() {
3266     },
3267     on_selection_changed: function() {
3268         if (this.reference_ready) {
3269             var sel = this.selection.get_value();
3270             this.m2o.field.relation = sel;
3271             this.m2o.set_value(null);
3272             this.m2o.$element.toggle(sel !== false);
3273         }
3274     },
3275     start: function() {
3276         var self = this;
3277         this._super();
3278         this.selection.start();
3279         this.m2o.start();
3280         $(this.selection).add($(this.m2o)).bind({
3281             'focus': function () { $(self).trigger('widget-focus'); },
3282             'blur': function () { $(self).trigger('widget-blur'); }
3283         })
3284     },
3285     is_valid: function() {
3286         return this.required === false || typeof(this.get_value()) === 'string';
3287     },
3288     is_dirty: function() {
3289         return this.selection.is_dirty() || this.m2o.is_dirty();
3290     },
3291     set_value: function(value) {
3292         this._super(value);
3293         this.reference_ready = false;
3294         var vals = [], sel_val, m2o_val;
3295         if (typeof(value) === 'string') {
3296             vals = value.split(',');
3297         }
3298         sel_val = vals[0] || false;
3299         m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
3300         this.selection.set_value(sel_val);
3301         this.m2o.field.relation = sel_val;
3302         this.m2o.set_value(m2o_val);
3303         this.m2o.$element.toggle(sel_val !== false);
3304         this.reference_ready = true;
3305     },
3306     get_value: function() {
3307         var model = this.selection.get_value(),
3308             id = this.m2o.get_value();
3309         if (typeof(model) === 'string' && typeof(id) === 'number') {
3310             return model + ',' + id;
3311         } else {
3312             return false;
3313         }
3314     }
3315 });
3316
3317 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
3318     init: function(view, node) {
3319         this._super(view, node);
3320         this.iframe = this.element_id + '_iframe';
3321         this.binary_value = false;
3322     },
3323     start: function() {
3324         this._super.apply(this, arguments);
3325         this.$element.find('input.oe-binary-file').change(this.on_file_change);
3326         this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3327         this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3328     },
3329     human_filesize : function(size) {
3330         var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3331         var i = 0;
3332         while (size >= 1024) {
3333             size /= 1024;
3334             ++i;
3335         }
3336         return size.toFixed(2) + ' ' + units[i];
3337     },
3338     on_file_change: function(e) {
3339         // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3340         // http://www.html5rocks.com/tutorials/file/dndfiles/
3341         // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3342         window[this.iframe] = this.on_file_uploaded;
3343         if ($(e.target).val() != '') {
3344             this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3345             this.$element.find('form.oe-binary-form').submit();
3346             this.$element.find('.oe-binary-progress').show();
3347             this.$element.find('.oe-binary').hide();
3348         }
3349     },
3350     on_file_uploaded: function(size, name, content_type, file_base64) {
3351         delete(window[this.iframe]);
3352         if (size === false) {
3353             this.do_warn("File Upload", "There was a problem while uploading your file");
3354             // TODO: use openerp web crashmanager
3355             console.warn("Error while uploading file : ", name);
3356         } else {
3357             this.on_file_uploaded_and_valid.apply(this, arguments);
3358             this.on_ui_change();
3359         }
3360         this.$element.find('.oe-binary-progress').hide();
3361         this.$element.find('.oe-binary').show();
3362     },
3363     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3364     },
3365     on_save_as: function() {
3366         $.blockUI();
3367         this.session.get_file({
3368             url: '/web/binary/saveas_ajax',
3369             data: {data: JSON.stringify({
3370                 model: this.view.dataset.model,
3371                 id: (this.view.datarecord.id || ''),
3372                 field: this.name,
3373                 filename_field: (this.node.attrs.filename || ''),
3374                 context: this.view.dataset.get_context()
3375             })},
3376             complete: $.unblockUI,
3377             error: openerp.webclient.crashmanager.on_rpc_error
3378         });
3379     },
3380     set_filename: function(value) {
3381         var filename = this.node.attrs.filename;
3382         if (this.view.fields[filename]) {
3383             this.view.fields[filename].set_value(value);
3384             this.view.fields[filename].on_ui_change();
3385         }
3386     },
3387     on_clear: function() {
3388         if (this.value !== false) {
3389             this.value = false;
3390             this.binary_value = false;
3391             this.on_ui_change();
3392         }
3393         return false;
3394     }
3395 });
3396
3397 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
3398     template: 'FieldBinaryFile',
3399     update_dom: function() {
3400         this._super.apply(this, arguments);
3401         this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
3402         this.$element.find('input[type=text]').prop('readonly', this.readonly);
3403     },
3404     set_value: function(value) {
3405         this._super.apply(this, arguments);
3406         var show_value;
3407         if (this.node.attrs.filename) {
3408             show_value = this.view.datarecord[this.node.attrs.filename] || '';
3409         } else {
3410             show_value = (value != null && value !== false) ? value : '';
3411         }
3412         this.$element.find('input').eq(0).val(show_value);
3413     },
3414     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3415         this.value = file_base64;
3416         this.binary_value = true;
3417         var show_value = name + " (" + this.human_filesize(size) + ")";
3418         this.$element.find('input').eq(0).val(show_value);
3419         this.set_filename(name);
3420     },
3421     on_clear: function() {
3422         this._super.apply(this, arguments);
3423         this.$element.find('input').eq(0).val('');
3424         this.set_filename('');
3425     }
3426 });
3427
3428 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
3429     template: 'FieldBinaryImage',
3430     start: function() {
3431         this._super.apply(this, arguments);
3432         this.$image = this.$element.find('img.oe-binary-image');
3433     },
3434     update_dom: function() {
3435         this._super.apply(this, arguments);
3436         this.$element.find('.oe-binary').toggle(!this.readonly);
3437     },
3438     set_value: function(value) {
3439         this._super.apply(this, arguments);
3440         this.set_image_maxwidth();
3441         var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
3442             this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
3443         this.$image.attr('src', url);
3444     },
3445     set_image_maxwidth: function() {
3446         this.$image.css('max-width', this.$element.width());
3447     },
3448     on_file_change: function() {
3449         this.set_image_maxwidth();
3450         this._super.apply(this, arguments);
3451     },
3452     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3453         this.value = file_base64;
3454         this.binary_value = true;
3455         this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
3456         this.set_filename(name);
3457     },
3458     on_clear: function() {
3459         this._super.apply(this, arguments);
3460         this.$image.attr('src', '/web/static/src/img/placeholder.png');
3461         this.set_filename('');
3462     }
3463 });
3464
3465 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
3466     template: "EmptyComponent",
3467     start: function() {
3468         this._super();
3469         this.selected_value = null;
3470
3471         this.render_list();
3472     },
3473     set_value: function(value) {
3474         this._super(value);
3475         this.selected_value = value;
3476
3477         this.render_list();
3478     },
3479     render_list: function() {
3480         var self = this;
3481         var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3482             function(x) { return _.str.trim(x); });
3483         shown = _.select(shown, function(x) { return x.length > 0; });
3484
3485         if (shown.length == 0) {
3486             this.to_show = this.field.selection;
3487         } else {
3488             this.to_show = _.select(this.field.selection, function(x) {
3489                 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3490             });
3491         }
3492
3493         var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3494         this.$element.html(content);
3495
3496         var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3497         var color = colors[this.selected_value];
3498         if (color) {
3499             var elem = this.$element.find("li.oe-arrow-list-selected span");
3500             elem.css("border-color", color);
3501             if (this.check_white(color))
3502                 elem.css("color", "white");
3503             elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3504             elem.css("border-left-color", "transparent");
3505             elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3506             elem.css("border-color", "transparent");
3507             elem.css("border-left-color", color);
3508         }
3509     },
3510     check_white: function(color) {
3511         var div = $("<div></div>");
3512         div.css("display", "none");
3513         div.css("color", color);
3514         div.appendTo($("body"));
3515         var ncolor = div.css("color");
3516         div.remove();
3517         var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3518         if (!res) {
3519             return false;
3520         }
3521         var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3522         var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3523         if (lum < 128) {
3524             return true;
3525         }
3526         return false;
3527     }
3528 });
3529
3530 openerp.web.form.WidgetHtml = openerp.web.form.Widget.extend({
3531     render: function () {
3532         var $root = $('<div class="oe_form_html_view">');
3533         this.render_children(this, $root);
3534         return $root.html();
3535     },
3536     render_children: function (object, $into) {
3537         var self = this,
3538             fields = this.view.fields_view.fields;
3539         _(object.children).each(function (child) {
3540             if (typeof child === 'string') {
3541                 $into.text(child);
3542             } else if (child.tag === 'field') {
3543                 $into.append(
3544                     new (self.view.registry.get_object('frame'))(
3545                         self.view, {tag: 'ueule', attrs: {}, children: [child] })
3546                             .render());
3547             } else {
3548                 var $child = $(document.createElement(child.tag))
3549                         .attr(child.attrs)
3550                         .appendTo($into);
3551                 self.render_children(child, $child);
3552             }
3553         });
3554     }
3555 });
3556
3557
3558 /**
3559  * Registry of form widgets, called by :js:`openerp.web.FormView`
3560  */
3561 openerp.web.form.widgets = new openerp.web.Registry({
3562     'frame' : 'openerp.web.form.WidgetFrame',
3563     'group' : 'openerp.web.form.WidgetGroup',
3564     'notebook' : 'openerp.web.form.WidgetNotebook',
3565     'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3566     'separator' : 'openerp.web.form.WidgetSeparator',
3567     'label' : 'openerp.web.form.WidgetLabel',
3568     'button' : 'openerp.web.form.WidgetButton',
3569     'char' : 'openerp.web.form.FieldChar',
3570     'id' : 'openerp.web.form.FieldID',
3571     'email' : 'openerp.web.form.FieldEmail',
3572     'url' : 'openerp.web.form.FieldUrl',
3573     'text' : 'openerp.web.form.FieldText',
3574     'date' : 'openerp.web.form.FieldDate',
3575     'datetime' : 'openerp.web.form.FieldDatetime',
3576     'selection' : 'openerp.web.form.FieldSelection',
3577     'many2one' : 'openerp.web.form.FieldMany2One',
3578     'many2many' : 'openerp.web.form.FieldMany2Many',
3579     'one2many' : 'openerp.web.form.FieldOne2Many',
3580     'one2many_list' : 'openerp.web.form.FieldOne2Many',
3581     'reference' : 'openerp.web.form.FieldReference',
3582     'boolean' : 'openerp.web.form.FieldBoolean',
3583     'float' : 'openerp.web.form.FieldFloat',
3584     'integer': 'openerp.web.form.FieldFloat',
3585     'float_time': 'openerp.web.form.FieldFloat',
3586     'progressbar': 'openerp.web.form.FieldProgressBar',
3587     'image': 'openerp.web.form.FieldBinaryImage',
3588     'binary': 'openerp.web.form.FieldBinaryFile',
3589     'statusbar': 'openerp.web.form.FieldStatus',
3590     'html': 'openerp.web.form.WidgetHtml'
3591 });
3592
3593
3594 };
3595
3596 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: