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