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