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