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