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