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