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