6a45bae5abd975912d5d60d9c1125ee49b058d79
[odoo/odoo.git] / addons / web / static / src / js / view_form.js
1 openerp.web.form = function (openerp) {
2
3 var _t = openerp.web._t,
4    _lt = openerp.web._lt;
5 var QWeb = openerp.web.qweb;
6
7 openerp.web.views.add('form', 'openerp.web.FormView');
8 openerp.web.FormView = openerp.web.View.extend( /** @lends openerp.web.FormView# */{
9     /**
10      * Indicates that this view is not searchable, and thus that no search
11      * view should be displayed (if there is one active).
12      */
13     searchable: false,
14     readonly : false,
15     form_template: "FormView",
16     display_name: _lt('Form'),
17     /**
18      * @constructs openerp.web.FormView
19      * @extends openerp.web.View
20      *
21      * @param {openerp.web.Session} session the current openerp session
22      * @param {openerp.web.DataSet} dataset the dataset this view will work with
23      * @param {String} view_id the identifier of the OpenERP view object
24      * @param {Object} options
25      *                  - sidebar : [true|false]
26      *                  - resize_textareas : [true|false|max_height]
27      *
28      * @property {openerp.web.Registry} registry=openerp.web.form.widgets widgets registry for this form view instance
29      */
30     init: function(parent, dataset, view_id, options) {
31         this._super(parent);
32         this.set_default_options(options);
33         this.dataset = dataset;
34         this.model = dataset.model;
35         this.view_id = view_id || false;
36         this.fields_view = {};
37         this.widgets = {};
38         this.widgets_counter = 0;
39         this.fields = {};
40         this.fields_order = [];
41         this.datarecord = {};
42         this.default_focus_field = null;
43         this.default_focus_button = null;
44         this.registry = openerp.web.form.widgets;
45         this.has_been_loaded = $.Deferred();
46         this.$form_header = null;
47         this.translatable_fields = [];
48         _.defaults(this.options, {
49             "not_interactible_on_create": false
50         });
51         this.is_initialized = $.Deferred();
52         this.mutating_mutex = new $.Mutex();
53         this.on_change_mutex = new $.Mutex();
54         this.reload_mutex = new $.Mutex();
55     },
56     start: function() {
57         this._super();
58         return this.init_view();
59     },
60     init_view: function() {
61         if (this.embedded_view) {
62             var def = $.Deferred().then(this.on_loaded);
63             var self = this;
64             $.async_when().then(function() {def.resolve(self.embedded_view);});
65             return def.promise();
66         } else {
67             var context = new openerp.web.CompoundContext(this.dataset.get_context());
68             return this.rpc("/web/view/load", {
69                 "model": this.model,
70                 "view_id": this.view_id,
71                 "view_type": "form",
72                 toolbar: this.options.sidebar,
73                 context: context
74                 }, this.on_loaded);
75         }
76     },
77     stop: function() {
78         if (this.sidebar) {
79             this.sidebar.attachments.stop();
80             this.sidebar.stop();
81         }
82         _.each(this.widgets, function(w) {
83             w.stop();
84         });
85         this._super();
86     },
87     reposition: function ($e) {
88         this.$element = $e;
89         this.on_loaded();
90     },
91     on_loaded: function(data) {
92         var self = this;
93         if (data) {
94             this.fields_order = [];
95             this.fields_view = data;
96             var frame = new (this.registry.get_object('frame'))(this, this.fields_view.arch);
97
98             this.rendered = QWeb.render(this.form_template, { 'frame': frame, 'widget': this });
99         }
100         this.$element.html(this.rendered);
101         _.each(this.widgets, function(w) {
102             w.start();
103         });
104         this.$form_header = this.$element.find('.oe_form_header:first');
105         this.$form_header.find('div.oe_form_pager button[data-pager-action]').click(function() {
106             var action = $(this).data('pager-action');
107             self.on_pager_action(action);
108         });
109
110         this.$form_header.find('button.oe_form_button_save').click(this.on_button_save);
111         this.$form_header.find('button.oe_form_button_cancel').click(this.on_button_cancel);
112
113         if (!this.sidebar && this.options.sidebar && this.options.sidebar_id) {
114             this.sidebar = new openerp.web.Sidebar(this, this.options.sidebar_id);
115             this.sidebar.start();
116             this.sidebar.do_unfold();
117             this.sidebar.attachments = new openerp.web.form.SidebarAttachments(this.sidebar, this);
118             this.sidebar.add_toolbar(this.fields_view.toolbar);
119             this.set_common_sidebar_sections(this.sidebar);
120
121             this.sidebar.add_section(_t('Customize'), 'customize');
122             this.sidebar.add_items('customize', [{
123                 label: _t('Set Default'),
124                 form: this,
125                 callback: function (item) {
126                     item.form.open_defaults_dialog();
127                 }
128             }]);
129         }
130         this.has_been_loaded.resolve();
131     },
132
133     do_load_state: function(state, warm) {
134         if (state.id && this.datarecord.id != state.id) {
135             if (!this.dataset.get_id_index(state.id)) {
136                 this.dataset.ids.push(state.id);
137             }
138             this.dataset.select_id(state.id);
139             if (warm) {
140                 this.do_show();
141             }
142         }
143     },
144
145     do_show: function () {
146         var self = this;
147         this.$element.show().css('visibility', 'hidden');
148         this.$element.removeClass('oe_form_dirty');
149         return this.has_been_loaded.pipe(function() {
150             var result;
151             if (self.dataset.index === null) {
152                 // null index means we should start a new record
153                 result = self.on_button_new();
154             } else {
155                 result = self.dataset.read_index(_.keys(self.fields_view.fields), {
156                     context : { 'bin_size' : true }
157                 }).pipe(self.on_record_loaded);
158             }
159             result.pipe(function() {
160                 self.$element.css('visibility', 'visible');
161             });
162             if (self.sidebar) {
163                 self.sidebar.$element.show();
164             }
165             return result;
166         });
167     },
168     do_hide: function () {
169         this._super();
170         if (this.sidebar) {
171             this.sidebar.$element.hide();
172         }
173     },
174     on_record_loaded: function(record) {
175         var self = this, set_values = [];
176         if (!record) {
177             this.do_warn("Form", "The record could not be found in the database.", true);
178             return $.Deferred().reject();
179         }
180         this.datarecord = record;
181
182         _(this.fields).each(function (field, f) {
183             field.reset();
184             var result = field.set_value(self.datarecord[f] || false);
185             set_values.push(result);
186             $.when(result).then(function() {
187                 field.validate();
188             });
189         });
190         return $.when.apply(null, set_values).pipe(function() {
191             if (!record.id) {
192                 // New record: Second pass in order to trigger the onchanges
193                 // respecting the fields order defined in the view
194                 _.each(self.fields_order, function(field_name) {
195                     if (record[field_name] !== undefined) {
196                         var field = self.fields[field_name];
197                         field.dirty = true;
198                         self.do_onchange(field);
199                     }
200                 });
201             }
202             self.on_form_changed();
203             self.is_initialized.resolve();
204             self.do_update_pager(record.id == null);
205             if (self.sidebar) {
206                 self.sidebar.attachments.do_update();
207             }
208             if (self.default_focus_field && !self.embedded_view) {
209                 self.default_focus_field.focus();
210             }
211             if (record.id) {
212                 self.do_push_state({id:record.id});
213             }
214             self.$element.removeClass('oe_form_dirty');
215         });
216     },
217     on_form_changed: function() {
218         for (var w in this.widgets) {
219             w = this.widgets[w];
220             w.process_modifiers();
221             if (w.field) {
222                 w.validate();
223             }
224             w.update_dom();
225         }
226     },
227     do_notify_change: function() {
228         this.$element.addClass('oe_form_dirty');
229     },
230     on_pager_action: function(action) {
231         if (this.can_be_discarded()) {
232             switch (action) {
233                 case 'first':
234                     this.dataset.index = 0;
235                     break;
236                 case 'previous':
237                     this.dataset.previous();
238                     break;
239                 case 'next':
240                     this.dataset.next();
241                     break;
242                 case 'last':
243                     this.dataset.index = this.dataset.ids.length - 1;
244                     break;
245             }
246             this.reload();
247         }
248     },
249     do_update_pager: function(hide_index) {
250         var $pager = this.$form_header.find('div.oe_form_pager');
251         var index = hide_index ? '-' : this.dataset.index + 1;
252         $pager.find('button').prop('disabled', this.dataset.ids.length < 2);
253         $pager.find('span.oe_pager_index').html(index);
254         $pager.find('span.oe_pager_count').html(this.dataset.ids.length);
255     },
256     parse_on_change: function (on_change, widget) {
257         var self = this;
258         var onchange = _.str.trim(on_change);
259         var call = onchange.match(/^\s?(.*?)\((.*?)\)\s?$/);
260         if (!call) {
261             return null;
262         }
263
264         var method = call[1];
265         if (!_.str.trim(call[2])) {
266             return {method: method, args: [], context_index: null}
267         }
268
269         var argument_replacement = {
270             'False': function () {return false;},
271             'True': function () {return true;},
272             'None': function () {return null;},
273             'context': function (i) {
274                 context_index = i;
275                 var ctx = new openerp.web.CompoundContext(self.dataset.get_context(), widget.build_context() ? widget.build_context() : {});
276                 return ctx;
277             }
278         };
279         var parent_fields = null, context_index = null;
280         var args = _.map(call[2].split(','), function (a, i) {
281             var field = _.str.trim(a);
282
283             // literal constant or context
284             if (field in argument_replacement) {
285                 return argument_replacement[field](i);
286             }
287             // literal number
288             if (/^-?\d+(\.\d+)?$/.test(field)) {
289                 return Number(field);
290             }
291             // form field
292             if (self.fields[field]) {
293                 var value = self.fields[field].get_on_change_value();
294                 return value == null ? false : value;
295             }
296             // parent field
297             var splitted = field.split('.');
298             if (splitted.length > 1 && _.str.trim(splitted[0]) === "parent" && self.dataset.parent_view) {
299                 if (parent_fields === null) {
300                     parent_fields = self.dataset.parent_view.get_fields_values([self.dataset.child_name]);
301                 }
302                 var p_val = parent_fields[_.str.trim(splitted[1])];
303                 if (p_val !== undefined) {
304                     return p_val == null ? false : p_val;
305                 }
306             }
307             // string literal
308             var first_char = field[0], last_char = field[field.length-1];
309             if ((first_char === '"' && last_char === '"')
310                 || (first_char === "'" && last_char === "'")) {
311                 return field.slice(1, -1);
312             }
313
314             throw new Error("Could not get field with name '" + field +
315                             "' for onchange '" + onchange + "'");
316         });
317
318         return {
319             method: method,
320             args: args,
321             context_index: context_index
322         };
323     },
324     do_onchange: function(widget, processed) {
325         var self = this;
326         return this.on_change_mutex.exec(function() {
327             try {
328                 var response = {}, can_process_onchange = $.Deferred();
329                 processed = processed || [];
330                 processed.push(widget.name);
331                 var on_change = widget.node.attrs.on_change;
332                 if (on_change) {
333                     var change_spec = self.parse_on_change(on_change, widget);
334                     if (change_spec) {
335                         var ajax = {
336                             url: '/web/dataset/onchange',
337                             async: false
338                         };
339                         can_process_onchange = self.rpc(ajax, {
340                             model: self.dataset.model,
341                             method: change_spec.method,
342                             args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args),
343                             context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1
344                         }).then(function(r) {
345                             _.extend(response, r);
346                         });
347                     } else {
348                         console.warn("Wrong on_change format", on_change);
349                     }
350                 }
351                 // fail if onchange failed
352                 if (can_process_onchange.isRejected()) {
353                     return can_process_onchange;
354                 }
355
356                 if (widget.field['change_default']) {
357                     var fieldname = widget.name, value;
358                     if (response.value && (fieldname in response.value)) {
359                         // Use value from onchange if onchange executed
360                         value = response.value[fieldname];
361                     } else {
362                         // otherwise get form value for field
363                         value = self.fields[fieldname].get_on_change_value();
364                     }
365                     var condition = fieldname + '=' + value;
366
367                     if (value) {
368                         can_process_onchange = self.rpc({
369                             url: '/web/dataset/call',
370                             async: false
371                         }, {
372                             model: 'ir.values',
373                             method: 'get_defaults',
374                             args: [self.model, condition]
375                         }).then(function (results) {
376                             if (!results.length) { return; }
377                             if (!response.value) {
378                                 response.value = {};
379                             }
380                             for(var i=0; i<results.length; ++i) {
381                                 // [whatever, key, value]
382                                 var triplet = results[i];
383                                 response.value[triplet[1]] = triplet[2];
384                             }
385                         });
386                     }
387                 }
388                 if (can_process_onchange.isRejected()) {
389                     return can_process_onchange;
390                 }
391
392                 return self.on_processed_onchange(response, processed);
393             } catch(e) {
394                 console.error(e);
395                 return $.Deferred().reject();
396             }
397         });
398     },
399     on_processed_onchange: function(response, processed) {
400         try {
401         var result = response;
402         if (result.value) {
403             for (var f in result.value) {
404                 if (!result.value.hasOwnProperty(f)) { continue; }
405                 var field = this.fields[f];
406                 // If field is not defined in the view, just ignore it
407                 if (field) {
408                     var value = result.value[f];
409                     if (field.get_value() != value) {
410                         field.set_value(value);
411                         field.dirty = true;
412                         if (!_.contains(processed, field.name)) {
413                             this.do_onchange(field, processed);
414                         }
415                     }
416                 }
417             }
418             this.on_form_changed();
419         }
420         if (!_.isEmpty(result.warning)) {
421             $(QWeb.render("CrashManagerWarning", result.warning)).dialog({
422                 modal: true,
423                 buttons: [
424                     {text: _t("Ok"), click: function() { $(this).dialog("close"); }}
425                 ]
426             });
427         }
428         if (result.domain) {
429             function edit_domain(node) {
430                 var new_domain = result.domain[node.attrs.name];
431                 if (new_domain) {
432                     node.attrs.domain = new_domain;
433                 }
434                 _(node.children).each(edit_domain);
435             }
436             edit_domain(this.fields_view.arch);
437         }
438         return $.Deferred().resolve();
439         } catch(e) {
440             console.error(e);
441             return $.Deferred().reject();
442         }
443     },
444     on_button_save: function() {
445         var self = this;
446         return this.do_save().then(function(result) {
447             self.do_prev_view({'created': result.created, 'default': 'page'});
448         });
449     },
450     on_button_cancel: function() {
451         if (this.can_be_discarded()) {
452             return this.do_prev_view({'default': 'page'});
453         }
454     },
455     on_button_new: function() {
456         var self = this;
457         var def = $.Deferred();
458         $.when(this.has_been_loaded).then(function() {
459             if (self.can_be_discarded()) {
460                 var keys = _.keys(self.fields_view.fields);
461                 if (keys.length) {
462                     self.dataset.default_get(keys).pipe(self.on_record_loaded).then(function() {
463                         def.resolve();
464                     });
465                 } else {
466                     self.on_record_loaded({}).then(function() {
467                         def.resolve();
468                     });
469                 }
470             }
471         });
472         return def.promise();
473     },
474     can_be_discarded: function() {
475         return !this.$element.is('.oe_form_dirty') || confirm(_t("Warning, the record has been modified, your changes will be discarded."));
476     },
477     /**
478      * Triggers saving the form's record. Chooses between creating a new
479      * record or saving an existing one depending on whether the record
480      * already has an id property.
481      *
482      * @param {Function} success callback on save success
483      * @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)
484      */
485     do_save: function(success, prepend_on_create) {
486         var self = this;
487         return this.mutating_mutex.exec(function() { return self.is_initialized.pipe(function() {
488             try {
489             var form_invalid = false,
490                 values = {},
491                 first_invalid_field = null;
492             for (var f in self.fields) {
493                 f = self.fields[f];
494                 if (!f.is_valid()) {
495                     form_invalid = true;
496                     f.update_dom(true);
497                     if (!first_invalid_field) {
498                         first_invalid_field = f;
499                     }
500                 } else if (f.name !== 'id' && !f.readonly && (!self.datarecord.id || f.is_dirty())) {
501                     // Special case 'id' field, do not save this field
502                     // on 'create' : save all non readonly fields
503                     // on 'edit' : save non readonly modified fields
504                     values[f.name] = f.get_value();
505                 }
506             }
507             if (form_invalid) {
508                 first_invalid_field.focus();
509                 self.on_invalid();
510                 return $.Deferred().reject();
511             } else {
512                 var save_deferral;
513                 if (!self.datarecord.id) {
514                     //console.log("FormView(", self, ") : About to create", values);
515                     save_deferral = self.dataset.create(values).pipe(function(r) {
516                         return self.on_created(r, undefined, prepend_on_create);
517                     }, null);
518                 } else if (_.isEmpty(values)) {
519                     //console.log("FormView(", self, ") : Nothing to save");
520                     save_deferral = $.Deferred().resolve({}).promise();
521                 } else {
522                     //console.log("FormView(", self, ") : About to save", values);
523                     save_deferral = self.dataset.write(self.datarecord.id, values, {}).pipe(function(r) {
524                         return self.on_saved(r);
525                     }, null);
526                 }
527                 return save_deferral.then(success);
528             }
529             } catch (e) {
530                 console.error(e);
531                 return $.Deferred().reject();
532             }
533         });});
534     },
535     on_invalid: function() {
536         var msg = "<ul>";
537         _.each(this.fields, function(f) {
538             if (!f.is_valid()) {
539                 msg += "<li>" + f.string + "</li>";
540             }
541         });
542         msg += "</ul>";
543         this.do_warn("The following fields are invalid :", msg);
544     },
545     on_saved: function(r, success) {
546         if (!r.result) {
547             // should not happen in the server, but may happen for internal purpose
548             return $.Deferred().reject();
549         } else {
550             return $.when(this.reload()).pipe(function () {
551                 return $.when(r).then(success); }, null);
552         }
553     },
554     /**
555      * Updates the form' dataset to contain the new record:
556      *
557      * * Adds the newly created record to the current dataset (at the end by
558      *   default)
559      * * Selects that record (sets the dataset's index to point to the new
560      *   record's id).
561      * * Updates the pager and sidebar displays
562      *
563      * @param {Object} r
564      * @param {Function} success callback to execute after having updated the dataset
565      * @param {Boolean} [prepend_on_create=false] adds the newly created record at the beginning of the dataset instead of the end
566      */
567     on_created: function(r, success, prepend_on_create) {
568         if (!r.result) {
569             // should not happen in the server, but may happen for internal purpose
570             return $.Deferred().reject();
571         } else {
572             this.datarecord.id = r.result;
573             if (!prepend_on_create) {
574                 this.dataset.alter_ids(this.dataset.ids.concat([this.datarecord.id]));
575                 this.dataset.index = this.dataset.ids.length - 1;
576             } else {
577                 this.dataset.alter_ids([this.datarecord.id].concat(this.dataset.ids));
578                 this.dataset.index = 0;
579             }
580             this.do_update_pager();
581             if (this.sidebar) {
582                 this.sidebar.attachments.do_update();
583             }
584             //openerp.log("The record has been created with id #" + this.datarecord.id);
585             this.reload();
586             return $.when(_.extend(r, {created: true})).then(success);
587         }
588     },
589     on_action: function (action) {
590         console.debug('Executing action', action);
591     },
592     reload: function() {
593         var self = this;
594         return this.reload_mutex.exec(function() {
595             if (self.dataset.index == null || self.dataset.index < 0) {
596                 return $.when(self.on_button_new());
597             } else {
598                 return self.dataset.read_index(_.keys(self.fields_view.fields), {
599                     context : { 'bin_size' : true }
600                 }).pipe(self.on_record_loaded);
601             }
602         });
603     },
604     get_fields_values: function(blacklist) {
605         blacklist = blacklist || [];
606         var values = {};
607         var ids = this.get_selected_ids();
608         values["id"] = ids.length > 0 ? ids[0] : false;
609         _.each(this.fields, function(value, key) {
610                 if (_.include(blacklist, key))
611                         return;
612             var val = value.get_value();
613             values[key] = val;
614         });
615         return values;
616     },
617     get_selected_ids: function() {
618         var id = this.dataset.ids[this.dataset.index];
619         return id ? [id] : [];
620     },
621     recursive_save: function() {
622         var self = this;
623         return $.when(this.do_save()).pipe(function(res) {
624             if (self.dataset.parent_view)
625                 return self.dataset.parent_view.recursive_save();
626         });
627     },
628     is_dirty: function() {
629         return _.any(this.fields, function (value) {
630             return value.is_dirty();
631         });
632     },
633     is_interactible_record: function() {
634         var id = this.datarecord.id;
635         if (!id) {
636             if (this.options.not_interactible_on_create)
637                 return false;
638         } else if (typeof(id) === "string") {
639             if(openerp.web.BufferedDataSet.virtual_id_regex.test(id))
640                 return false;
641         }
642         return true;
643     },
644     sidebar_context: function () {
645         return this.do_save().pipe(_.bind(function() {return this.get_fields_values();}, this));
646     },
647     open_defaults_dialog: function () {
648         var self = this;
649         var fields = _.chain(this.fields)
650             .map(function (field, name) {
651                 var value = field.get_value();
652                 // ignore fields which are empty, invisible, readonly, o2m
653                 // or m2m
654                 if (!value
655                         || field.invisible
656                         || field.readonly
657                         || field.field.type === 'one2many'
658                         || field.field.type === 'many2many') {
659                     return false;
660                 }
661                 var displayed;
662                 switch(field.field.type) {
663                 case 'selection':
664                     displayed = _(field.values).find(function (option) {
665                             return option[0] === value;
666                         })[1];
667                     break;
668                 case 'many2one':
669                     displayed = field.value[1] || value;
670                     break;
671                 default:
672                     displayed = value;
673                 }
674
675                 return {
676                     name: name,
677                     string: field.string,
678                     value: value,
679                     displayed: displayed,
680                     // convert undefined to false
681                     change_default: !!field.field.change_default
682                 }
683             })
684             .compact()
685             .sortBy(function (field) { return field.string; })
686             .value();
687         var conditions = _.chain(fields)
688             .filter(function (field) { return field.change_default; })
689             .value();
690
691         var d = new openerp.web.Dialog(this, {
692             title: _t("Set Default"),
693             args: {
694                 fields: fields,
695                 conditions: conditions
696             },
697             buttons: [
698                 {text: _t("Close"), click: function () { d.close(); }},
699                 {text: _t("Save default"), click: function () {
700                     var $defaults = d.$element.find('#formview_default_fields');
701                     var field_to_set = $defaults.val();
702                     if (!field_to_set) {
703                         $defaults.parent().addClass('invalid');
704                         return;
705                     }
706                     var condition = d.$element.find('#formview_default_conditions').val(),
707                         all_users = d.$element.find('#formview_default_all').is(':checked');
708                     new openerp.web.DataSet(self, 'ir.values').call(
709                         'set_default', [
710                             self.dataset.model,
711                             field_to_set,
712                             self.fields[field_to_set].get_value(),
713                             all_users,
714                             false,
715                             condition || false
716                     ]).then(function () { d.close(); });
717                 }}
718             ]
719         });
720         d.template = 'FormView.set_default';
721         d.open();
722     }
723 });
724 openerp.web.FormDialog = openerp.web.Dialog.extend({
725     init: function(parent, options, view_id, dataset) {
726         this._super(parent, options);
727         this.dataset = dataset;
728         this.view_id = view_id;
729         return this;
730     },
731     start: function() {
732         this._super();
733         this.form = new openerp.web.FormView(this, this.dataset, this.view_id, {
734             sidebar: false,
735             pager: false
736         });
737         this.form.appendTo(this.$element);
738         this.form.on_created.add_last(this.on_form_dialog_saved);
739         this.form.on_saved.add_last(this.on_form_dialog_saved);
740         return this;
741     },
742     select_id: function(id) {
743         if (this.form.dataset.select_id(id)) {
744             return this.form.do_show();
745         } else {
746             this.do_warn("Could not find id in dataset");
747             return $.Deferred().reject();
748         }
749     },
750     on_form_dialog_saved: function(r) {
751         this.close();
752     }
753 });
754
755 /** @namespace */
756 openerp.web.form = {};
757
758 openerp.web.form.SidebarAttachments = openerp.web.OldWidget.extend({
759     init: function(parent, form_view) {
760         var $section = parent.add_section(_t('Attachments'), 'attachments');
761         this.$div = $('<div class="oe-sidebar-attachments"></div>');
762         $section.append(this.$div);
763
764         this._super(parent, $section.attr('id'));
765         this.view = form_view;
766     },
767     do_update: function() {
768         if (!this.view.datarecord.id) {
769             this.on_attachments_loaded([]);
770         } else {
771             (new openerp.web.DataSetSearch(
772                 this, 'ir.attachment', this.view.dataset.get_context(),
773                 [
774                     ['res_model', '=', this.view.dataset.model],
775                     ['res_id', '=', this.view.datarecord.id],
776                     ['type', 'in', ['binary', 'url']]
777                 ])).read_slice(['name', 'url', 'type'], {}).then(this.on_attachments_loaded);
778         }
779     },
780     on_attachments_loaded: function(attachments) {
781         this.attachments = attachments;
782         this.$div.html(QWeb.render('FormView.sidebar.attachments', this));
783         this.$element.find('.oe-binary-file').change(this.on_attachment_changed);
784         this.$element.find('.oe-sidebar-attachment-delete').click(this.on_attachment_delete);
785     },
786     on_attachment_changed: function(e) {
787         window[this.element_id + '_iframe'] = this.do_update;
788         var $e = $(e.target);
789         if ($e.val() != '') {
790             this.$element.find('form.oe-binary-form').submit();
791             $e.parent().find('input[type=file]').prop('disabled', true);
792             $e.parent().find('button').prop('disabled', true).find('img, span').toggle();
793         }
794     },
795     on_attachment_delete: function(e) {
796         var self = this, $e = $(e.currentTarget);
797         var name = _.str.trim($e.parent().find('a.oe-sidebar-attachments-link').text());
798         if (confirm(_.str.sprintf(_t("Do you really want to delete the attachment %s?"), name))) {
799             this.rpc('/web/dataset/unlink', {
800                 model: 'ir.attachment',
801                 ids: [parseInt($e.attr('data-id'))]
802             }, function(r) {
803                 $e.parent().remove();
804                 self.do_notify("Delete an attachment", "The attachment '" + name + "' has been deleted");
805             });
806         }
807     }
808 });
809
810 openerp.web.form.compute_domain = function(expr, fields) {
811     var stack = [];
812     for (var i = expr.length - 1; i >= 0; i--) {
813         var ex = expr[i];
814         if (ex.length == 1) {
815             var top = stack.pop();
816             switch (ex) {
817                 case '|':
818                     stack.push(stack.pop() || top);
819                     continue;
820                 case '&':
821                     stack.push(stack.pop() && top);
822                     continue;
823                 case '!':
824                     stack.push(!top);
825                     continue;
826                 default:
827                     throw new Error(_.str.sprintf(
828                         _t("Unknown operator %s in domain %s"),
829                         ex, JSON.stringify(expr)));
830             }
831         }
832
833         var field = fields[ex[0]];
834         if (!field) {
835             throw new Error(_.str.sprintf(
836                 _t("Unknown field %s in domain %s"),
837                 ex[0], JSON.stringify(expr)));
838         }
839         var field_value = field.get_value ? fields[ex[0]].get_value() : fields[ex[0]].value;
840         var op = ex[1];
841         var val = ex[2];
842
843         switch (op.toLowerCase()) {
844             case '=':
845             case '==':
846                 stack.push(field_value == val);
847                 break;
848             case '!=':
849             case '<>':
850                 stack.push(field_value != val);
851                 break;
852             case '<':
853                 stack.push(field_value < val);
854                 break;
855             case '>':
856                 stack.push(field_value > val);
857                 break;
858             case '<=':
859                 stack.push(field_value <= val);
860                 break;
861             case '>=':
862                 stack.push(field_value >= val);
863                 break;
864             case 'in':
865                 if (!_.isArray(val)) val = [val];
866                 stack.push(_(val).contains(field_value));
867                 break;
868             case 'not in':
869                 if (!_.isArray(val)) val = [val];
870                 stack.push(!_(val).contains(field_value));
871                 break;
872             default:
873                 console.warn(
874                     _t("Unsupported operator %s in domain %s"),
875                     op, JSON.stringify(expr));
876         }
877     }
878     return _.all(stack, _.identity);
879 };
880
881 openerp.web.form.Widget = openerp.web.OldWidget.extend(/** @lends openerp.web.form.Widget# */{
882     template: 'Widget',
883     /**
884      * @constructs openerp.web.form.Widget
885      * @extends openerp.web.OldWidget
886      *
887      * @param view
888      * @param node
889      */
890     init: function(view, node) {
891         this.view = view;
892         this.node = node;
893         this.modifiers = JSON.parse(this.node.attrs.modifiers || '{}');
894         this.always_invisible = (this.modifiers.invisible && this.modifiers.invisible === true);
895         this.type = this.type || node.tag;
896         this.element_name = this.element_name || this.type;
897         this.element_class = [
898             'formview', this.view.view_id, this.element_name,
899             this.view.widgets_counter++].join("_");
900
901         this._super(view);
902
903         this.view.widgets[this.element_class] = this;
904         this.children = node.children;
905         this.colspan = parseInt(node.attrs.colspan || 1, 10);
906         this.decrease_max_width = 0;
907
908         this.string = this.string || node.attrs.string;
909         this.help = this.help || node.attrs.help;
910         this.invisible = this.modifiers['invisible'] === true;
911         this.classname = 'oe_form_' + this.type;
912
913         this.align = parseFloat(this.node.attrs.align);
914         if (isNaN(this.align) || this.align === 1) {
915             this.align = 'right';
916         } else if (this.align === 0) {
917             this.align = 'left';
918         } else {
919             this.align = 'center';
920         }
921
922
923         this.width = this.node.attrs.width;
924     },
925     start: function() {
926         this.$element = this.view.$element.find(
927             '.' + this.element_class.replace(/[^\r\n\f0-9A-Za-z_-]/g, "\\$&"));
928     },
929     stop: function() {
930         this._super.apply(this, arguments);
931         $.fn.tipsy.clear();
932     },
933     process_modifiers: function() {
934         var compute_domain = openerp.web.form.compute_domain;
935         for (var a in this.modifiers) {
936             this[a] = compute_domain(this.modifiers[a], this.view.fields);
937         }
938     },
939     update_dom: function() {
940         this.$element.toggle(!this.invisible);
941     },
942     render: function() {
943         var template = this.template;
944         return QWeb.render(template, { "widget": this });
945     },
946     do_attach_tooltip: function(widget, trigger, options) {
947         widget = widget || this;
948         trigger = trigger || this.$element;
949         options = _.extend({
950                 delayIn: 500,
951                 delayOut: 0,
952                 fade: true,
953                 title: function() {
954                     var template = widget.template + '.tooltip';
955                     if (!QWeb.has_template(template)) {
956                         template = 'WidgetLabel.tooltip';
957                     }
958                     return QWeb.render(template, {
959                         debug: openerp.connection.debug,
960                         widget: widget
961                 })},
962                 gravity: $.fn.tipsy.autoBounds(50, 'nw'),
963                 html: true,
964                 opacity: 0.85,
965                 trigger: 'hover'
966             }, options || {});
967         trigger.tipsy(options);
968     },
969     _build_view_fields_values: function(blacklist) {
970         var a_dataset = this.view.dataset;
971         var fields_values = this.view.get_fields_values(blacklist);
972         var active_id = a_dataset.ids[a_dataset.index];
973         _.extend(fields_values, {
974             active_id: active_id || false,
975             active_ids: active_id ? [active_id] : [],
976             active_model: a_dataset.model,
977             parent: {}
978         });
979         if (a_dataset.parent_view) {
980                 fields_values.parent = a_dataset.parent_view.get_fields_values([a_dataset.child_name]);
981         }
982         return fields_values;
983     },
984     _build_eval_context: function(blacklist) {
985         var a_dataset = this.view.dataset;
986         return new openerp.web.CompoundContext(a_dataset.get_context(), this._build_view_fields_values(blacklist));
987     },
988     /**
989      * Builds a new context usable for operations related to fields by merging
990      * the fields'context with the action's context.
991      */
992     build_context: function(blacklist) {
993         // only use the model's context if there is not context on the node
994         var v_context = this.node.attrs.context;
995         if (! v_context) {
996             v_context = (this.field || {}).context || {};
997         }
998         
999         if (v_context.__ref || true) { //TODO: remove true
1000             var fields_values = this._build_eval_context(blacklist);
1001             v_context = new openerp.web.CompoundContext(v_context).set_eval_context(fields_values);
1002         }
1003         return v_context;
1004     },
1005     build_domain: function() {
1006         var f_domain = this.field.domain || [];
1007         var n_domain = this.node.attrs.domain || null;
1008         // if there is a domain on the node, overrides the model's domain
1009         var final_domain = n_domain !== null ? n_domain : f_domain;
1010         if (!(final_domain instanceof Array) || true) { //TODO: remove true
1011             var fields_values = this._build_eval_context();
1012             final_domain = new openerp.web.CompoundDomain(final_domain).set_eval_context(fields_values);
1013         }
1014         return final_domain;
1015     }
1016 });
1017
1018 openerp.web.form.WidgetFrame = openerp.web.form.Widget.extend({
1019     template: 'WidgetFrame',
1020     init: function(view, node) {
1021         this._super(view, node);
1022         this.columns = parseInt(node.attrs.col || 4, 10);
1023         this.x = 0;
1024         this.y = 0;
1025         this.table = [];
1026         this.add_row();
1027         for (var i = 0; i < node.children.length; i++) {
1028             var n = node.children[i];
1029             if (n.tag == "newline") {
1030                 this.add_row();
1031             } else {
1032                 this.handle_node(n);
1033             }
1034         }
1035         this.set_row_cells_with(this.table[this.table.length - 1]);
1036     },
1037     add_row: function(){
1038         if (this.table.length) {
1039             this.set_row_cells_with(this.table[this.table.length - 1]);
1040         }
1041         var row = [];
1042         this.table.push(row);
1043         this.x = 0;
1044         this.y += 1;
1045         return row;
1046     },
1047     set_row_cells_with: function(row) {
1048         var bypass = 0,
1049             max_width = 100,
1050             row_length = row.length;
1051         for (var i = 0; i < row.length; i++) {
1052             if (row[i].always_invisible) {
1053                 row_length--;
1054             } else {
1055                 bypass += row[i].width === undefined ? 0 : 1;
1056                 max_width -= row[i].decrease_max_width;
1057             }
1058         }
1059         var size_unit = Math.round(max_width / (this.columns - bypass)),
1060             colspan_sum = 0;
1061         for (var i = 0; i < row.length; i++) {
1062             var w = row[i];
1063             if (w.always_invisible) {
1064                 continue;
1065             }
1066             colspan_sum += w.colspan;
1067             if (w.width === undefined) {
1068                 var width = (i === row_length - 1 && colspan_sum === this.columns) ? max_width : Math.round(size_unit * w.colspan);
1069                 max_width -= width;
1070                 w.width = width + '%';
1071             }
1072         }
1073     },
1074     handle_node: function(node) {
1075         var type = {};
1076         if (node.tag == 'field') {
1077             type = this.view.fields_view.fields[node.attrs.name] || {};
1078             if (node.attrs.widget == 'statusbar' && node.attrs.nolabel !== '1') {
1079                 // This way we can retain backward compatibility between addons and old clients
1080                 node.attrs.colspan = (parseInt(node.attrs.colspan, 10) || 1) + 1;
1081                 node.attrs.nolabel = '1';
1082             }
1083         }
1084         var widget = new (this.view.registry.get_any(
1085                 [node.attrs.widget, type.type, node.tag])) (this.view, node);
1086         if (node.tag == 'field') {
1087             if (!this.view.default_focus_field || node.attrs.default_focus == '1') {
1088                 this.view.default_focus_field = widget;
1089             }
1090             if (node.attrs.nolabel != '1') {
1091                 var label = new (this.view.registry.get_object('label')) (this.view, node);
1092                 label["for"] = widget;
1093                 this.add_widget(label, widget.colspan + 1);
1094             }
1095         }
1096         this.add_widget(widget);
1097     },
1098     add_widget: function(widget, colspan) {
1099         var current_row = this.table[this.table.length - 1];
1100         if (!widget.always_invisible) {
1101             colspan = colspan || widget.colspan;
1102             if (current_row.length && (this.x + colspan) > this.columns) {
1103                 current_row = this.add_row();
1104             }
1105             this.x += widget.colspan;
1106         }
1107         current_row.push(widget);
1108         return widget;
1109     }
1110 });
1111
1112 openerp.web.form.WidgetGroup = openerp.web.form.WidgetFrame.extend({
1113     template: 'WidgetGroup'
1114 }),
1115
1116 openerp.web.form.WidgetNotebook = openerp.web.form.Widget.extend({
1117     template: 'WidgetNotebook',
1118     init: function(view, node) {
1119         this._super(view, node);
1120         this.pages = [];
1121         for (var i = 0; i < node.children.length; i++) {
1122             var n = node.children[i];
1123             if (n.tag == "page") {
1124                 var page = new (this.view.registry.get_object('notebookpage'))(
1125                         this.view, n, this, this.pages.length);
1126                 this.pages.push(page);
1127             }
1128         }
1129     },
1130     start: function() {
1131         var self = this;
1132         this._super.apply(this, arguments);
1133         this.$element.find('> ul > li').each(function (index, tab_li) {
1134             var page = self.pages[index],
1135                 id = _.uniqueId(self.element_name + '-');
1136             page.element_id = id;
1137             $(tab_li).find('a').attr('href', '#' + id);
1138         });
1139         this.$element.find('> div').each(function (index, page) {
1140             page.id = self.pages[index].element_id;
1141         });
1142         this.$element.tabs();
1143         this.view.on_button_new.add_first(this.do_select_first_visible_tab);
1144         if (openerp.connection.debug) {
1145             this.do_attach_tooltip(this, this.$element.find('ul:first'), {
1146                 gravity: 's'
1147             });
1148         }
1149     },
1150     do_select_first_visible_tab: function() {
1151         for (var i = 0; i < this.pages.length; i++) {
1152             var page = this.pages[i];
1153             if (page.invisible === false) {
1154                 this.$element.tabs('select', page.index);
1155                 break;
1156             }
1157         }
1158     }
1159 });
1160
1161 openerp.web.form.WidgetNotebookPage = openerp.web.form.WidgetFrame.extend({
1162     template: 'WidgetNotebookPage',
1163     init: function(view, node, notebook, index) {
1164         this.notebook = notebook;
1165         this.index = index;
1166         this.element_name = 'page_' + index;
1167         this._super(view, node);
1168     },
1169     start: function() {
1170         this._super.apply(this, arguments);
1171         this.$element_tab = this.notebook.$element.find(
1172                 '> ul > li:eq(' + this.index + ')');
1173     },
1174     update_dom: function() {
1175         if (this.invisible && this.index === this.notebook.$element.tabs('option', 'selected')) {
1176             this.notebook.do_select_first_visible_tab();
1177         }
1178         this.$element_tab.toggle(!this.invisible);
1179         this.$element.toggle(!this.invisible);
1180     }
1181 });
1182
1183 openerp.web.form.WidgetSeparator = openerp.web.form.Widget.extend({
1184     template: 'WidgetSeparator',
1185     init: function(view, node) {
1186         this._super(view, node);
1187         this.orientation = node.attrs.orientation || 'horizontal';
1188         if (this.orientation === 'vertical') {
1189             this.width = '1';
1190         }
1191         this.classname += '_' + this.orientation;
1192     }
1193 });
1194
1195 openerp.web.form.WidgetButton = openerp.web.form.Widget.extend({
1196     template: 'WidgetButton',
1197     init: function(view, node) {
1198         this._super(view, node);
1199         this.force_disabled = false;
1200         if (this.string) {
1201             // We don't have button key bindings in the webclient
1202             this.string = this.string.replace(/_/g, '');
1203         }
1204         if (node.attrs.default_focus == '1') {
1205             // TODO fme: provide enter key binding to widgets
1206             this.view.default_focus_button = this;
1207         }
1208     },
1209     start: function() {
1210         this._super.apply(this, arguments);
1211         this.$element.find("button").click(this.on_click);
1212         if (this.help || openerp.connection.debug) {
1213             this.do_attach_tooltip();
1214         }
1215     },
1216     on_click: function() {
1217         var self = this;
1218         this.force_disabled = true;
1219         this.check_disable();
1220         this.execute_action().always(function() {
1221             self.force_disabled = false;
1222             self.check_disable();
1223         });
1224     },
1225     execute_action: function() {
1226         var self = this;
1227         var exec_action = function() {
1228             if (self.node.attrs.confirm) {
1229                 var def = $.Deferred();
1230                 var dialog = $('<div>' + self.node.attrs.confirm + '</div>').dialog({
1231                     title: _t('Confirm'),
1232                     modal: true,
1233                     buttons: [
1234                         {text: _t("Cancel"), click: function() {
1235                                 def.resolve();
1236                                 $(this).dialog("close");
1237                             }
1238                         },
1239                         {text: _t("Ok"), click: function() {
1240                                 self.on_confirmed().then(function() {
1241                                     def.resolve();
1242                                 });
1243                                 $(this).dialog("close");
1244                             }
1245                         }
1246                     ]
1247                 });
1248                 return def.promise();
1249             } else {
1250                 return self.on_confirmed();
1251             }
1252         };
1253         if (!this.node.attrs.special) {
1254             return this.view.recursive_save().pipe(exec_action);
1255         } else {
1256             return exec_action();
1257         }
1258     },
1259     on_confirmed: function() {
1260         var self = this;
1261
1262         var context = this.node.attrs.context;
1263         if (context && context.__ref) {
1264             context = new openerp.web.CompoundContext(context);
1265             context.set_eval_context(this._build_eval_context());
1266         }
1267
1268         return this.view.do_execute_action(
1269             _.extend({}, this.node.attrs, {context: context}),
1270             this.view.dataset, this.view.datarecord.id, function () {
1271                 self.view.reload();
1272             });
1273     },
1274     update_dom: function() {
1275         this._super.apply(this, arguments);
1276         this.check_disable();
1277     },
1278     check_disable: function() {
1279         var disabled = (this.readonly || this.force_disabled || !this.view.is_interactible_record());
1280         this.$element.find('button').prop('disabled', disabled);
1281         this.$element.find("button").css('color', disabled ? 'grey' : '');
1282     }
1283 });
1284
1285 openerp.web.form.WidgetLabel = openerp.web.form.Widget.extend({
1286     template: 'WidgetLabel',
1287     init: function(view, node) {
1288         this.element_name = 'label_' + node.attrs.name;
1289
1290         this._super(view, node);
1291
1292         if (this.node.tag == 'label' && !this.string && this.node.children.length) {
1293             this.string = this.node.children[0];
1294             this.align = 'left';
1295         }
1296
1297         if (this.node.tag == 'label' && (this.align === 'left' || this.node.attrs.colspan || (this.string && this.string.length > 32))) {
1298             this.template = "WidgetParagraph";
1299             this.colspan = parseInt(this.node.attrs.colspan || 1, 10);
1300             // Widgets default to right-aligned, but paragraph defaults to
1301             // left-aligned
1302             if (isNaN(parseFloat(this.node.attrs.align))) {
1303                 this.align = 'left';
1304             }
1305
1306             this.multilines = this.string && _.str.lines(this.string).length > 1;
1307         } else {
1308             this.colspan = 1;
1309             this.width = '1%';
1310             this.decrease_max_width = 1;
1311             this.nowrap = true;
1312         }
1313     },
1314     render: function () {
1315         if (this['for'] && this.type !== 'label') {
1316             return QWeb.render(this.template, {widget: this['for']});
1317         }
1318         // Actual label widgets should not have a false and have type label
1319         return QWeb.render(this.template, {widget: this});
1320     },
1321     start: function() {
1322         this._super();
1323         var self = this;
1324         if (this['for'] && (this['for'].help || openerp.connection.debug)) {
1325             this.do_attach_tooltip(self['for']);
1326         }
1327         this.$element.find("label").dblclick(function() {
1328             var widget = self['for'] || self;
1329             openerp.log(widget.element_class , widget);
1330             window.w = widget;
1331         });
1332     }
1333 });
1334
1335 openerp.web.form.Field = openerp.web.form.Widget.extend(/** @lends openerp.web.form.Field# */{
1336     /**
1337      * @constructs openerp.web.form.Field
1338      * @extends openerp.web.form.Widget
1339      *
1340      * @param view
1341      * @param node
1342      */
1343     init: function(view, node) {
1344         this.name = node.attrs.name;
1345         this.value = undefined;
1346         view.fields[this.name] = this;
1347         view.fields_order.push(this.name);
1348         this.type = node.attrs.widget || view.fields_view.fields[node.attrs.name].type;
1349         this.element_name = "field_" + this.name + "_" + this.type;
1350
1351         this._super(view, node);
1352
1353         if (node.attrs.nolabel != '1' && this.colspan > 1) {
1354             this.colspan--;
1355         }
1356         this.field = view.fields_view.fields[node.attrs.name] || {};
1357         this.string = node.attrs.string || this.field.string;
1358         this.help = node.attrs.help || this.field.help;
1359         this.nolabel = (this.field.nolabel || node.attrs.nolabel) === '1';
1360         this.readonly = this.modifiers['readonly'] === true;
1361         this.required = this.modifiers['required'] === true;
1362         this.invalid = this.dirty = false;
1363
1364         this.classname = 'oe_form_field_' + this.type;
1365     },
1366     start: function() {
1367         this._super.apply(this, arguments);
1368         if (this.field.translate) {
1369             this.view.translatable_fields.push(this);
1370             this.$element.addClass('oe_form_field_translatable');
1371             this.$element.find('.oe_field_translate').click(this.on_translate);
1372         }
1373         if (this.nolabel && openerp.connection.debug) {
1374             this.do_attach_tooltip(this, this.$element);
1375         }
1376     },
1377     set_value: function(value) {
1378         this.value = value;
1379         this.invalid = false;
1380         this.update_dom();
1381         this.on_value_changed();
1382     },
1383     set_value_from_ui: function() {
1384         this.on_value_changed();
1385     },
1386     on_value_changed: function() {
1387     },
1388     on_translate: function() {
1389         this.view.open_translate_dialog(this);
1390     },
1391     get_value: function() {
1392         return this.value;
1393     },
1394     is_valid: function() {
1395         return !this.invalid;
1396     },
1397     is_dirty: function() {
1398         return this.dirty && !this.readonly;
1399     },
1400     get_on_change_value: function() {
1401         return this.get_value();
1402     },
1403     update_dom: function(show_invalid) {
1404         this._super.apply(this, arguments);
1405         if (this.field.translate) {
1406             this.$element.find('.oe_field_translate').toggle(!!this.view.datarecord.id);
1407         }
1408         if (!this.disable_utility_classes) {
1409             this.$element.toggleClass('disabled', this.readonly);
1410             this.$element.toggleClass('required', this.required);
1411             if (show_invalid) {
1412                 this.$element.toggleClass('invalid', !this.is_valid());
1413             }
1414         }
1415     },
1416     on_ui_change: function() {
1417         this.dirty = true;
1418         this.validate();
1419         if (this.is_valid()) {
1420             this.set_value_from_ui();
1421             this.view.do_onchange(this);
1422             this.view.on_form_changed(true);
1423             this.view.do_notify_change();
1424         } else {
1425             this.update_dom(true);
1426         }
1427     },
1428     validate: function() {
1429         this.invalid = false;
1430     },
1431     focus: function($element) {
1432         if ($element) {
1433             setTimeout(function() {
1434                 $element.focus();
1435             }, 50);
1436         }
1437     },
1438     reset: function() {
1439         this.dirty = false;
1440     },
1441     get_definition_options: function() {
1442         if (!this.definition_options) {
1443             var str = this.node.attrs.options || '{}';
1444             this.definition_options = JSON.parse(str);
1445         }
1446         return this.definition_options;
1447     }
1448 });
1449
1450 openerp.web.form.FieldChar = openerp.web.form.Field.extend({
1451     template: 'FieldChar',
1452     init: function (view, node) {
1453         this._super(view, node);
1454         this.password = this.node.attrs.password === 'True' || this.node.attrs.password === '1';
1455     },
1456     start: function() {
1457         this._super.apply(this, arguments);
1458         this.$element.find('input').change(this.on_ui_change);
1459     },
1460     set_value: function(value) {
1461         this._super.apply(this, arguments);
1462         var show_value = openerp.web.format_value(value, this, '');
1463         this.$element.find('input').val(show_value);
1464         return show_value;
1465     },
1466     update_dom: function() {
1467         this._super.apply(this, arguments);
1468         this.$element.find('input').prop('readonly', this.readonly);
1469     },
1470     set_value_from_ui: function() {
1471         this.value = openerp.web.parse_value(this.$element.find('input').val(), this);
1472         this._super();
1473     },
1474     validate: function() {
1475         this.invalid = false;
1476         try {
1477             var value = openerp.web.parse_value(this.$element.find('input').val(), this, '');
1478             this.invalid = this.required && value === '';
1479         } catch(e) {
1480             this.invalid = true;
1481         }
1482     },
1483     focus: function($element) {
1484         this._super($element || this.$element.find('input:first'));
1485     }
1486 });
1487
1488 openerp.web.form.FieldID = openerp.web.form.FieldChar.extend({
1489     update_dom: function() {
1490         this._super.apply(this, arguments);
1491         this.$element.find('input').prop('readonly', true);
1492     }
1493 });
1494
1495 openerp.web.form.FieldEmail = openerp.web.form.FieldChar.extend({
1496     template: 'FieldEmail',
1497     start: function() {
1498         this._super.apply(this, arguments);
1499         this.$element.find('button').click(this.on_button_clicked);
1500     },
1501     on_button_clicked: function() {
1502         if (!this.value || !this.is_valid()) {
1503             this.do_warn("E-mail error", "Can't send email to invalid e-mail address");
1504         } else {
1505             location.href = 'mailto:' + this.value;
1506         }
1507     }
1508 });
1509
1510 openerp.web.form.FieldUrl = openerp.web.form.FieldChar.extend({
1511     template: 'FieldUrl',
1512     start: function() {
1513         this._super.apply(this, arguments);
1514         this.$element.find('button').click(this.on_button_clicked);
1515     },
1516     on_button_clicked: function() {
1517         if (!this.value) {
1518             this.do_warn("Resource error", "This resource is empty");
1519         } else {
1520             window.open(this.value);
1521         }
1522     }
1523 });
1524
1525 openerp.web.form.FieldFloat = openerp.web.form.FieldChar.extend({
1526     init: function (view, node) {
1527         this._super(view, node);
1528         if (node.attrs.digits) {
1529             this.parse_digits(node.attrs.digits);
1530         } else {
1531             this.digits = view.fields_view.fields[node.attrs.name].digits;
1532         }
1533     },
1534     parse_digits: function (digits_attr) {
1535         // could use a Python parser instead.
1536         var match = /^\s*[\(\[](\d+),\s*(\d+)/.exec(digits_attr);
1537         return [parseInt(match[1], 10), parseInt(match[2], 10)];
1538     },
1539     set_value: function(value) {
1540         if (value === false || value === undefined) {
1541             // As in GTK client, floats default to 0
1542             value = 0;
1543         }
1544         this._super.apply(this, [value]);
1545     }
1546 });
1547
1548 openerp.web.DateTimeWidget = openerp.web.OldWidget.extend({
1549     template: "web.datetimepicker",
1550     jqueryui_object: 'datetimepicker',
1551     type_of_date: "datetime",
1552     init: function(parent) {
1553         this._super(parent);
1554         this.name = parent.name;
1555     },
1556     start: function() {
1557         var self = this;
1558         this.$input = this.$element.find('input.oe_datepicker_master');
1559         this.$input_picker = this.$element.find('input.oe_datepicker_container');
1560         this.$input.change(this.on_change);
1561         this.picker({
1562             onSelect: this.on_picker_select,
1563             changeMonth: true,
1564             changeYear: true,
1565             showWeek: true,
1566             showButtonPanel: true
1567         });
1568         this.$element.find('img.oe_datepicker_trigger').click(function() {
1569             if (!self.readonly && !self.picker('widget').is(':visible')) {
1570                 self.picker('setDate', self.value ? openerp.web.auto_str_to_date(self.value) : new Date());
1571                 self.$input_picker.show();
1572                 self.picker('show');
1573                 self.$input_picker.hide();
1574             }
1575         });
1576         this.set_readonly(false);
1577         this.value = false;
1578     },
1579     picker: function() {
1580         return $.fn[this.jqueryui_object].apply(this.$input_picker, arguments);
1581     },
1582     on_picker_select: function(text, instance) {
1583         var date = this.picker('getDate');
1584         this.$input.val(date ? this.format_client(date) : '').change();
1585     },
1586     set_value: function(value) {
1587         this.value = value;
1588         this.$input.val(value ? this.format_client(value) : '');
1589     },
1590     get_value: function() {
1591         return this.value;
1592     },
1593     set_value_from_ui: function() {
1594         var value = this.$input.val() || false;
1595         this.value = this.parse_client(value);
1596     },
1597     set_readonly: function(readonly) {
1598         this.readonly = readonly;
1599         this.$input.prop('readonly', this.readonly);
1600         this.$element.find('img.oe_datepicker_trigger').toggleClass('oe_input_icon_disabled', readonly);
1601     },
1602     is_valid: function(required) {
1603         var value = this.$input.val();
1604         if (value === "") {
1605             return !required;
1606         } else {
1607             try {
1608                 this.parse_client(value);
1609                 return true;
1610             } catch(e) {
1611                 return false;
1612             }
1613         }
1614     },
1615     parse_client: function(v) {
1616         return openerp.web.parse_value(v, {"widget": this.type_of_date});
1617     },
1618     format_client: function(v) {
1619         return openerp.web.format_value(v, {"widget": this.type_of_date});
1620     },
1621     on_change: function() {
1622         if (this.is_valid()) {
1623             this.set_value_from_ui();
1624         }
1625     }
1626 });
1627
1628 openerp.web.DateWidget = openerp.web.DateTimeWidget.extend({
1629     jqueryui_object: 'datepicker',
1630     type_of_date: "date"
1631 });
1632
1633 openerp.web.form.FieldDatetime = openerp.web.form.Field.extend({
1634     template: "EmptyComponent",
1635     build_widget: function() {
1636         return new openerp.web.DateTimeWidget(this);
1637     },
1638     start: function() {
1639         var self = this;
1640         this._super.apply(this, arguments);
1641         this.datewidget = this.build_widget();
1642         this.datewidget.on_change.add_last(this.on_ui_change);
1643         this.datewidget.appendTo(this.$element);
1644     },
1645     set_value: function(value) {
1646         this._super(value);
1647         this.datewidget.set_value(value);
1648     },
1649     get_value: function() {
1650         return this.datewidget.get_value();
1651     },
1652     update_dom: function() {
1653         this._super.apply(this, arguments);
1654         this.datewidget.set_readonly(this.readonly);
1655     },
1656     validate: function() {
1657         this.invalid = !this.datewidget.is_valid(this.required);
1658     },
1659     focus: function($element) {
1660         this._super($element || this.datewidget.$input);
1661     }
1662 });
1663
1664 openerp.web.form.FieldDate = openerp.web.form.FieldDatetime.extend({
1665     build_widget: function() {
1666         return new openerp.web.DateWidget(this);
1667     }
1668 });
1669
1670 openerp.web.form.FieldText = openerp.web.form.Field.extend({
1671     template: 'FieldText',
1672     start: function() {
1673         this._super.apply(this, arguments);
1674         this.$element.find('textarea').change(this.on_ui_change);
1675         this.resized = false;
1676     },
1677     set_value: function(value) {
1678         this._super.apply(this, arguments);
1679         var show_value = openerp.web.format_value(value, this, '');
1680         this.$element.find('textarea').val(show_value);
1681         if (!this.resized && this.view.options.resize_textareas) {
1682             this.do_resize(this.view.options.resize_textareas);
1683             this.resized = true;
1684         }
1685     },
1686     update_dom: function() {
1687         this._super.apply(this, arguments);
1688         this.$element.find('textarea').prop('readonly', this.readonly);
1689     },
1690     set_value_from_ui: function() {
1691         this.value = openerp.web.parse_value(this.$element.find('textarea').val(), this);
1692         this._super();
1693     },
1694     validate: function() {
1695         this.invalid = false;
1696         try {
1697             var value = openerp.web.parse_value(this.$element.find('textarea').val(), this, '');
1698             this.invalid = this.required && value === '';
1699         } catch(e) {
1700             this.invalid = true;
1701         }
1702     },
1703     focus: function($element) {
1704         this._super($element || this.$element.find('textarea:first'));
1705     },
1706     do_resize: function(max_height) {
1707         max_height = parseInt(max_height, 10);
1708         var $input = this.$element.find('textarea'),
1709             $div = $('<div style="position: absolute; z-index: 1000; top: 0"/>').width($input.width()),
1710             new_height;
1711         $div.text($input.val());
1712         _.each('font-family,font-size,white-space'.split(','), function(style) {
1713             $div.css(style, $input.css(style));
1714         });
1715         $div.appendTo($('body'));
1716         new_height = $div.height();
1717         if (new_height < 90) {
1718             new_height = 90;
1719         }
1720         if (!isNaN(max_height) && new_height > max_height) {
1721             new_height = max_height;
1722         }
1723         $div.remove();
1724         $input.height(new_height);
1725     },
1726     reset: function() {
1727         this.resized = false;
1728     }
1729 });
1730
1731 openerp.web.form.FieldBoolean = openerp.web.form.Field.extend({
1732     template: 'FieldBoolean',
1733     start: function() {
1734         var self = this;
1735         this._super.apply(this, arguments);
1736         this.$element.find('input').click(self.on_ui_change);
1737     },
1738     set_value: function(value) {
1739         this._super.apply(this, arguments);
1740         this.$element.find('input')[0].checked = value;
1741     },
1742     set_value_from_ui: function() {
1743         this.value = this.$element.find('input').is(':checked');
1744         this._super();
1745     },
1746     update_dom: function() {
1747         this._super.apply(this, arguments);
1748         this.$element.find('input').prop('disabled', this.readonly);
1749     },
1750     focus: function($element) {
1751         this._super($element || this.$element.find('input:first'));
1752     }
1753 });
1754
1755 openerp.web.form.FieldProgressBar = openerp.web.form.Field.extend({
1756     template: 'FieldProgressBar',
1757     start: function() {
1758         this._super.apply(this, arguments);
1759         this.$element.find('div').progressbar({
1760             value: this.value,
1761             disabled: this.readonly
1762         });
1763     },
1764     set_value: function(value) {
1765         this._super.apply(this, arguments);
1766         var show_value = Number(value);
1767         if (isNaN(show_value)) {
1768             show_value = 0;
1769         }
1770         var formatted_value = openerp.web.format_value(show_value, { type : 'float' }, '0');
1771         this.$element.find('div').progressbar('option', 'value', show_value).find('span').html(formatted_value + '%');
1772     }
1773 });
1774
1775 openerp.web.form.FieldTextXml = openerp.web.form.Field.extend({
1776 // to replace view editor
1777 });
1778
1779 openerp.web.form.FieldSelection = openerp.web.form.Field.extend({
1780     template: 'FieldSelection',
1781     init: function(view, node) {
1782         var self = this;
1783         this._super(view, node);
1784         this.values = _.clone(this.field.selection);
1785         _.each(this.values, function(v, i) {
1786             if (v[0] === false && v[1] === '') {
1787                 self.values.splice(i, 1);
1788             }
1789         });
1790         this.values.unshift([false, '']);
1791     },
1792     start: function() {
1793         // Flag indicating whether we're in an event chain containing a change
1794         // event on the select, in order to know what to do on keyup[RETURN]:
1795         // * If the user presses [RETURN] as part of changing the value of a
1796         //   selection, we should just let the value change and not let the
1797         //   event broadcast further (e.g. to validating the current state of
1798         //   the form in editable list view, which would lead to saving the
1799         //   current row or switching to the next one)
1800         // * If the user presses [RETURN] with a select closed (side-effect:
1801         //   also if the user opened the select and pressed [RETURN] without
1802         //   changing the selected value), takes the action as validating the
1803         //   row
1804         var ischanging = false;
1805         this._super.apply(this, arguments);
1806         this.$element.find('select')
1807             .change(this.on_ui_change)
1808             .change(function () { ischanging = true; })
1809             .click(function () { ischanging = false; })
1810             .keyup(function (e) {
1811                 if (e.which !== 13 || !ischanging) { return; }
1812                 e.stopPropagation();
1813                 ischanging = false;
1814             });
1815     },
1816     set_value: function(value) {
1817         value = value === null ? false : value;
1818         value = value instanceof Array ? value[0] : value;
1819         this._super(value);
1820         var index = 0;
1821         for (var i = 0, ii = this.values.length; i < ii; i++) {
1822             if (this.values[i][0] === value) index = i;
1823         }
1824         this.$element.find('select')[0].selectedIndex = index;
1825     },
1826     set_value_from_ui: function() {
1827         this.value = this.values[this.$element.find('select')[0].selectedIndex][0];
1828         this._super();
1829     },
1830     update_dom: function() {
1831         this._super.apply(this, arguments);
1832         this.$element.find('select').prop('disabled', this.readonly);
1833     },
1834     validate: function() {
1835         var value = this.values[this.$element.find('select')[0].selectedIndex];
1836         this.invalid = !(value && !(this.required && value[0] === false));
1837     },
1838     focus: function($element) {
1839         this._super($element || this.$element.find('select:first'));
1840     }
1841 });
1842
1843 // jquery autocomplete tweak to allow html
1844 (function() {
1845     var proto = $.ui.autocomplete.prototype,
1846         initSource = proto._initSource;
1847
1848     function filter( array, term ) {
1849         var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
1850         return $.grep( array, function(value) {
1851             return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
1852         });
1853     }
1854
1855     $.extend( proto, {
1856         _initSource: function() {
1857             if ( this.options.html && $.isArray(this.options.source) ) {
1858                 this.source = function( request, response ) {
1859                     response( filter( this.options.source, request.term ) );
1860                 };
1861             } else {
1862                 initSource.call( this );
1863             }
1864         },
1865
1866         _renderItem: function( ul, item) {
1867             return $( "<li></li>" )
1868                 .data( "item.autocomplete", item )
1869                 .append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
1870                 .appendTo( ul );
1871         }
1872     });
1873 })();
1874
1875 openerp.web.form.dialog = function(content, options) {
1876     options = _.extend({
1877         width: '90%',
1878         height: 'auto',
1879         min_width: '800px'
1880     }, options || {});
1881     var dialog = new openerp.web.Dialog(null, options, content).open();
1882     return dialog.$element;
1883 };
1884
1885 openerp.web.form.FieldMany2One = openerp.web.form.Field.extend({
1886     template: 'FieldMany2One',
1887     init: function(view, node) {
1888         this._super(view, node);
1889         this.limit = 7;
1890         this.value = null;
1891         this.cm_id = _.uniqueId('m2o_cm_');
1892         this.last_search = [];
1893         this.tmp_value = undefined;
1894     },
1895     start: function() {
1896         this._super();
1897         var self = this;
1898         this.$input = this.$element.find("input");
1899         this.$drop_down = this.$element.find(".oe-m2o-drop-down-button");
1900         this.$menu_btn = this.$element.find(".oe-m2o-cm-button");
1901
1902         // context menu
1903         var init_context_menu_def = $.Deferred().then(function(e) {
1904             var rdataset = new openerp.web.DataSetStatic(self, "ir.values", self.build_context());
1905             rdataset.call("get", ['action', 'client_action_relate',
1906                 [[self.field.relation, false]], false, rdataset.get_context()], false, 0)
1907                 .then(function(result) {
1908                 self.related_entries = result;
1909
1910                 var $cmenu = $("#" + self.cm_id);
1911                 $cmenu.append(QWeb.render("FieldMany2One.context_menu", {widget: self}));
1912                 var bindings = {};
1913                 bindings[self.cm_id + "_search"] = function() {
1914                     if (self.readonly)
1915                         return;
1916                     self._search_create_popup("search");
1917                 };
1918                 bindings[self.cm_id + "_create"] = function() {
1919                     if (self.readonly)
1920                         return;
1921                     self._search_create_popup("form");
1922                 };
1923                 bindings[self.cm_id + "_open"] = function() {
1924                     if (!self.value) {
1925                         return;
1926                     }
1927                     var pop = new openerp.web.form.FormOpenPopup(self.view);
1928                     pop.show_element(
1929                         self.field.relation,
1930                         self.value[0],
1931                         self.build_context(),
1932                         {
1933                             title: _t("Open: ") + (self.string || self.name)
1934                         }
1935                     );
1936                     pop.on_write_completed.add_last(function() {
1937                         self.set_value(self.value[0]);
1938                     });
1939                 };
1940                 _.each(_.range(self.related_entries.length), function(i) {
1941                     bindings[self.cm_id + "_related_" + i] = function() {
1942                         self.open_related(self.related_entries[i]);
1943                     };
1944                 });
1945                 var cmenu = self.$menu_btn.contextMenu(self.cm_id, {'noRightClick': true,
1946                     bindings: bindings, itemStyle: {"color": ""},
1947                     onContextMenu: function() {
1948                         if(self.value) {
1949                             $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").removeClass("oe-m2o-disabled-cm");
1950                         } else {
1951                             $("#" + self.cm_id + " .oe_m2o_menu_item_mandatory").addClass("oe-m2o-disabled-cm");
1952                         }
1953                         if (!self.readonly) {
1954                             $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").removeClass("oe-m2o-disabled-cm");
1955                         } else {
1956                             $("#" + self.cm_id + " .oe_m2o_menu_item_noreadonly").addClass("oe-m2o-disabled-cm");
1957                         }
1958                         return true;
1959                     }, menuStyle: {width: "200px"}
1960                 });
1961                 $.async_when().then(function() {self.$menu_btn.trigger(e);});
1962             });
1963         });
1964         var ctx_callback = function(e) {init_context_menu_def.resolve(e); e.preventDefault()};
1965         this.$menu_btn.click(ctx_callback);
1966
1967         // some behavior for input
1968         this.$input.keyup(function() {
1969             if (self.$input.val() === "") {
1970                 self._change_int_value(null);
1971             } else if (self.value === null || (self.value && self.$input.val() !== self.value[1])) {
1972                 self._change_int_value(undefined);
1973             }
1974         });
1975         this.$drop_down.click(function() {
1976             if (self.readonly)
1977                 return;
1978             if (self.$input.autocomplete("widget").is(":visible")) {
1979                 self.$input.autocomplete("close");
1980             } else {
1981                 if (self.value) {
1982                     self.$input.autocomplete("search", "");
1983                 } else {
1984                     self.$input.autocomplete("search");
1985                 }
1986                 self.$input.focus();
1987             }
1988         });
1989         var anyoneLoosesFocus = function() {
1990             if (!self.$input.is(":focus") &&
1991                     !self.$input.autocomplete("widget").is(":visible") &&
1992                     !self.value) {
1993                 if (self.value === undefined && self.last_search.length > 0) {
1994                     self._change_int_ext_value(self.last_search[0]);
1995                 } else {
1996                     self._change_int_ext_value(null);
1997                 }
1998             }
1999         };
2000         this.$input.focusout(anyoneLoosesFocus);
2001
2002         var isSelecting = false;
2003         // autocomplete
2004         this.$input.autocomplete({
2005             source: function(req, resp) { self.get_search_result(req, resp); },
2006             select: function(event, ui) {
2007                 isSelecting = true;
2008                 var item = ui.item;
2009                 if (item.id) {
2010                     self._change_int_value([item.id, item.name]);
2011                 } else if (item.action) {
2012                     self._change_int_value(undefined);
2013                     item.action();
2014                     return false;
2015                 }
2016             },
2017             focus: function(e, ui) {
2018                 e.preventDefault();
2019             },
2020             html: true,
2021             close: anyoneLoosesFocus,
2022             minLength: 0,
2023             delay: 0
2024         });
2025         // used to correct a bug when selecting an element by pushing 'enter' in an editable list
2026         this.$input.keyup(function(e) {
2027             if (e.which === 13) {
2028                 if (isSelecting)
2029                     e.stopPropagation();
2030             }
2031             isSelecting = false;
2032         });
2033     },
2034     // autocomplete component content handling
2035     get_search_result: function(request, response) {
2036         var search_val = request.term;
2037         var self = this;
2038
2039         if (this.abort_last) {
2040             this.abort_last();
2041             delete this.abort_last;
2042         }
2043         var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2044
2045         dataset.name_search(search_val, self.build_domain(), 'ilike',
2046                 this.limit + 1, function(data) {
2047             self.last_search = data;
2048             // possible selections for the m2o
2049             var values = _.map(data, function(x) {
2050                 return {
2051                     label: _.str.escapeHTML(x[1]),
2052                     value:x[1],
2053                     name:x[1],
2054                     id:x[0]
2055                 };
2056             });
2057
2058             // search more... if more results that max
2059             if (values.length > self.limit) {
2060                 values = values.slice(0, self.limit);
2061                 values.push({label: _t("<em>   Search More...</em>"), action: function() {
2062                     dataset.name_search(search_val, self.build_domain(), 'ilike'
2063                     , false, function(data) {
2064                         self._change_int_value(null);
2065                         self._search_create_popup("search", data);
2066                     });
2067                 }});
2068             }
2069             // quick create
2070             var raw_result = _(data.result).map(function(x) {return x[1];});
2071             if (search_val.length > 0 &&
2072                 !_.include(raw_result, search_val) &&
2073                 (!self.value || search_val !== self.value[1])) {
2074                 values.push({label: _.str.sprintf(_t('<em>   Create "<strong>%s</strong>"</em>'),
2075                         $('<span />').text(search_val).html()), action: function() {
2076                     self._quick_create(search_val);
2077                 }});
2078             }
2079             // create...
2080             values.push({label: _t("<em>   Create and Edit...</em>"), action: function() {
2081                 self._change_int_value(null);
2082                 self._search_create_popup("form", undefined, {"default_name": search_val});
2083             }});
2084
2085             response(values);
2086         });
2087         this.abort_last = dataset.abort_last;
2088     },
2089     _quick_create: function(name) {
2090         var self = this;
2091         var slow_create = function () {
2092             self._change_int_value(null);
2093             self._search_create_popup("form", undefined, {"default_name": name});
2094         };
2095         if (self.get_definition_options().quick_create === undefined || self.get_definition_options().quick_create) {
2096             var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.build_context());
2097             dataset.name_create(name, function(data) {
2098                 self._change_int_ext_value(data);
2099             }).fail(function(error, event) {
2100                 event.preventDefault();
2101                 slow_create();
2102             });
2103         } else
2104             slow_create();
2105     },
2106     // all search/create popup handling
2107     _search_create_popup: function(view, ids, context) {
2108         var self = this;
2109         var pop = new openerp.web.form.SelectCreatePopup(this);
2110         pop.select_element(
2111             self.field.relation,
2112             {
2113                 title: (view === 'search' ? _t("Search: ") : _t("Create: ")) + (this.string || this.name),
2114                 initial_ids: ids ? _.map(ids, function(x) {return x[0]}) : undefined,
2115                 initial_view: view,
2116                 disable_multiple_selection: true
2117             },
2118             self.build_domain(),
2119             new openerp.web.CompoundContext(self.build_context(), context || {})
2120         );
2121         pop.on_select_elements.add(function(element_ids) {
2122             var dataset = new openerp.web.DataSetStatic(self, self.field.relation, self.build_context());
2123             dataset.name_get([element_ids[0]], function(data) {
2124                 self._change_int_ext_value(data[0]);
2125             });
2126         });
2127     },
2128     _change_int_ext_value: function(value) {
2129         this._change_int_value(value);
2130         this.$input.val(this.value ? this.value[1] : "");
2131     },
2132     _change_int_value: function(value) {
2133         this.value = value;
2134         var back_orig_value = this.original_value;
2135         if (this.value === null || this.value) {
2136             this.original_value = this.value;
2137         }
2138         if (back_orig_value === undefined) { // first use after a set_value()
2139             return;
2140         }
2141         if (this.value !== undefined && ((back_orig_value ? back_orig_value[0] : null)
2142                 !== (this.value ? this.value[0] : null))) {
2143             this.on_ui_change();
2144         }
2145     },
2146     set_value: function(value) {
2147         value = value || null;
2148         this.invalid = false;
2149         var self = this;
2150         this.tmp_value = value;
2151         self.update_dom();
2152         self.on_value_changed();
2153         var real_set_value = function(rval) {
2154             self.tmp_value = undefined;
2155             self.value = rval;
2156             self.original_value = undefined;
2157             self._change_int_ext_value(rval);
2158         };
2159         if (value && !(value instanceof Array)) {
2160             // name_get in a m2o does not use the context of the field
2161             var dataset = new openerp.web.DataSetStatic(this, this.field.relation, self.view.dataset.get_context());
2162             dataset.name_get([value], function(data) {
2163                 real_set_value(data[0]);
2164             }).fail(function() {self.tmp_value = undefined;});
2165         } else {
2166             $.async_when().then(function() {real_set_value(value);});
2167         }
2168     },
2169     get_value: function() {
2170         if (this.tmp_value !== undefined) {
2171             if (this.tmp_value instanceof Array) {
2172                 return this.tmp_value[0];
2173             }
2174             return this.tmp_value ? this.tmp_value : false;
2175         }
2176         if (this.value === undefined)
2177             return this.original_value ? this.original_value[0] : false;
2178         return this.value ? this.value[0] : false;
2179     },
2180     validate: function() {
2181         this.invalid = false;
2182         var val = this.tmp_value !== undefined ? this.tmp_value : this.value;
2183         if (val === null) {
2184             this.invalid = this.required;
2185         }
2186     },
2187     open_related: function(related) {
2188         var self = this;
2189         if (!self.value)
2190             return;
2191         var additional_context = {
2192                 active_id: self.value[0],
2193                 active_ids: [self.value[0]],
2194                 active_model: self.field.relation
2195         };
2196         self.rpc("/web/action/load", {
2197             action_id: related[2].id,
2198             context: additional_context
2199         }, function(result) {
2200             result.result.context = _.extend(result.result.context || {}, additional_context);
2201             self.do_action(result.result);
2202         });
2203     },
2204     focus: function ($element) {
2205         this._super($element || this.$input);
2206     },
2207     update_dom: function() {
2208         this._super.apply(this, arguments);
2209         this.$input.prop('readonly', this.readonly);
2210     }
2211 });
2212
2213 /*
2214 # Values: (0, 0,  { fields })    create
2215 #         (1, ID, { fields })    update
2216 #         (2, ID)                remove (delete)
2217 #         (3, ID)                unlink one (target id or target of relation)
2218 #         (4, ID)                link
2219 #         (5)                    unlink all (only valid for one2many)
2220 */
2221 var commands = {
2222     // (0, _, {values})
2223     CREATE: 0,
2224     'create': function (values) {
2225         return [commands.CREATE, false, values];
2226     },
2227     // (1, id, {values})
2228     UPDATE: 1,
2229     'update': function (id, values) {
2230         return [commands.UPDATE, id, values];
2231     },
2232     // (2, id[, _])
2233     DELETE: 2,
2234     'delete': function (id) {
2235         return [commands.DELETE, id, false];
2236     },
2237     // (3, id[, _]) removes relation, but not linked record itself
2238     FORGET: 3,
2239     'forget': function (id) {
2240         return [commands.FORGET, id, false];
2241     },
2242     // (4, id[, _])
2243     LINK_TO: 4,
2244     'link_to': function (id) {
2245         return [commands.LINK_TO, id, false];
2246     },
2247     // (5[, _[, _]])
2248     DELETE_ALL: 5,
2249     'delete_all': function () {
2250         return [5, false, false];
2251     },
2252     // (6, _, ids) replaces all linked records with provided ids
2253     REPLACE_WITH: 6,
2254     'replace_with': function (ids) {
2255         return [6, false, ids];
2256     }
2257 };
2258 openerp.web.form.FieldOne2Many = openerp.web.form.Field.extend({
2259     template: 'FieldOne2Many',
2260     multi_selection: false,
2261     init: function(view, node) {
2262         this._super(view, node);
2263         this.is_loaded = $.Deferred();
2264         this.initial_is_loaded = this.is_loaded;
2265         this.is_setted = $.Deferred();
2266         this.form_last_update = $.Deferred();
2267         this.init_form_last_update = this.form_last_update;
2268         this.disable_utility_classes = true;
2269     },
2270     start: function() {
2271         this._super.apply(this, arguments);
2272
2273         var self = this;
2274
2275         this.dataset = new openerp.web.form.One2ManyDataSet(this, this.field.relation);
2276         this.dataset.o2m = this;
2277         this.dataset.parent_view = this.view;
2278         this.dataset.child_name = this.name;
2279         //this.dataset.child_name = 
2280         this.dataset.on_change.add_last(function() {
2281             self.trigger_on_change();
2282         });
2283
2284         this.is_setted.then(function() {
2285             self.load_views();
2286         });
2287     },
2288     trigger_on_change: function() {
2289         var tmp = this.doing_on_change;
2290         this.doing_on_change = true;
2291         this.on_ui_change();
2292         this.doing_on_change = tmp;
2293     },
2294     is_readonly: function() {
2295         return this.readonly || this.force_readonly;
2296     },
2297     load_views: function() {
2298         var self = this;
2299         
2300         var modes = this.node.attrs.mode;
2301         modes = !!modes ? modes.split(",") : ["tree"];
2302         var views = [];
2303         _.each(modes, function(mode) {
2304             var view = {
2305                 view_id: false,
2306                 view_type: mode == "tree" ? "list" : mode,
2307                 options: { sidebar : false }
2308             };
2309             if (self.field.views && self.field.views[mode]) {
2310                 view.embedded_view = self.field.views[mode];
2311             }
2312             if(view.view_type === "list") {
2313                 view.options.selectable = self.multi_selection;
2314                 if (self.is_readonly()) {
2315                     view.options.addable = null;
2316                     view.options.deletable = null;
2317                     view.options.isClarkGable = false;
2318                 }
2319             } else if (view.view_type === "form") {
2320                 if (self.is_readonly()) {
2321                     view.view_type = 'page';
2322                 }
2323                 view.options.not_interactible_on_create = true;
2324             }
2325             views.push(view);
2326         });
2327         this.views = views;
2328
2329         this.viewmanager = new openerp.web.ViewManager(this, this.dataset, views, {});
2330         this.viewmanager.template = 'One2Many.viewmanager';
2331         this.viewmanager.registry = openerp.web.views.extend({
2332             list: 'openerp.web.form.One2ManyListView',
2333             form: 'openerp.web.form.One2ManyFormView',
2334             page: 'openerp.web.PageView'
2335         });
2336         var once = $.Deferred().then(function() {
2337             self.init_form_last_update.resolve();
2338         });
2339         var def = $.Deferred().then(function() {
2340             self.initial_is_loaded.resolve();
2341         });
2342         this.viewmanager.on_controller_inited.add_last(function(view_type, controller) {
2343             if (view_type == "list") {
2344                 controller.o2m = self;
2345                 if (self.is_readonly())
2346                     controller.set_editable(false);
2347             } else if (view_type == "form" || view_type == 'page') {
2348                 if (view_type == 'page' || self.is_readonly()) {
2349                     $(".oe_form_buttons", controller.$element).children().remove();
2350                 }
2351                 controller.on_record_loaded.add_last(function() {
2352                     once.resolve();
2353                 });
2354                 controller.on_pager_action.add_first(function() {
2355                     self.save_any_view();
2356                 });
2357             } else if (view_type == "graph") {
2358                 self.reload_current_view()
2359             }
2360             def.resolve();
2361         });
2362         this.viewmanager.on_mode_switch.add_first(function(n_mode, b, c, d, e) {
2363             $.when(self.save_any_view()).then(function() {
2364                 if(n_mode === "list")
2365                     $.async_when().then(function() {self.reload_current_view();});
2366             });
2367         });
2368         this.is_setted.then(function() {
2369             $.async_when().then(function () {
2370                 self.viewmanager.appendTo(self.$element);
2371             });
2372         });
2373         return def;
2374     },
2375     reload_current_view: function() {
2376         var self = this;
2377         return self.is_loaded = self.is_loaded.pipe(function() {
2378             var active_view = self.viewmanager.active_view;
2379             var view = self.viewmanager.views[active_view].controller;
2380             if(active_view === "list") {
2381                 return view.reload_content();
2382             } else if (active_view === "form" || active_view === 'page') {
2383                 if (self.dataset.index === null && self.dataset.ids.length >= 1) {
2384                     self.dataset.index = 0;
2385                 }
2386                 var act = function() {
2387                     return view.do_show();
2388                 };
2389                 self.form_last_update = self.form_last_update.pipe(act, act);
2390                 return self.form_last_update;
2391             } else if (active_view === "graph") {
2392                 return view.do_search(self.build_domain(), self.dataset.get_context(), []);
2393             }
2394         }, undefined);
2395     },
2396     set_value: function(value) {
2397         value = value || [];
2398         var self = this;
2399         this.dataset.reset_ids([]);
2400         if(value.length >= 1 && value[0] instanceof Array) {
2401             var ids = [];
2402             _.each(value, function(command) {
2403                 var obj = {values: command[2]};
2404                 switch (command[0]) {
2405                     case commands.CREATE:
2406                         obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2407                         obj.defaults = {};
2408                         self.dataset.to_create.push(obj);
2409                         self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2410                         ids.push(obj.id);
2411                         return;
2412                     case commands.UPDATE:
2413                         obj['id'] = command[1];
2414                         self.dataset.to_write.push(obj);
2415                         self.dataset.cache.push(_.extend(_.clone(obj), {values: _.clone(command[2])}));
2416                         ids.push(obj.id);
2417                         return;
2418                     case commands.DELETE:
2419                         self.dataset.to_delete.push({id: command[1]});
2420                         return;
2421                     case commands.LINK_TO:
2422                         ids.push(command[1]);
2423                         return;
2424                     case commands.DELETE_ALL:
2425                         self.dataset.delete_all = true;
2426                         return;
2427                 }
2428             });
2429             this._super(ids);
2430             this.dataset.set_ids(ids);
2431         } else if (value.length >= 1 && typeof(value[0]) === "object") {
2432             var ids = [];
2433             this.dataset.delete_all = true;
2434             _.each(value, function(command) {
2435                 var obj = {values: command};
2436                 obj['id'] = _.uniqueId(self.dataset.virtual_id_prefix);
2437                 obj.defaults = {};
2438                 self.dataset.to_create.push(obj);
2439                 self.dataset.cache.push(_.clone(obj));
2440                 ids.push(obj.id);
2441             });
2442             this._super(ids);
2443             this.dataset.set_ids(ids);
2444         } else {
2445             this._super(value);
2446             this.dataset.reset_ids(value);
2447         }
2448         if (this.dataset.index === null && this.dataset.ids.length > 0) {
2449             this.dataset.index = 0;
2450         }
2451         self.is_setted.resolve();
2452         return self.reload_current_view();
2453     },
2454     get_value: function() {
2455         var self = this;
2456         if (!this.dataset)
2457             return [];
2458         this.save_any_view();
2459         var val = this.dataset.delete_all ? [commands.delete_all()] : [];
2460         val = val.concat(_.map(this.dataset.ids, function(id) {
2461             var alter_order = _.detect(self.dataset.to_create, function(x) {return x.id === id;});
2462             if (alter_order) {
2463                 return commands.create(alter_order.values);
2464             }
2465             alter_order = _.detect(self.dataset.to_write, function(x) {return x.id === id;});
2466             if (alter_order) {
2467                 return commands.update(alter_order.id, alter_order.values);
2468             }
2469             return commands.link_to(id);
2470         }));
2471         return val.concat(_.map(
2472             this.dataset.to_delete, function(x) {
2473                 return commands['delete'](x.id);}));
2474     },
2475     save_any_view: function() {
2476         if (this.doing_on_change)
2477             return false;
2478         return this.session.synchronized_mode(_.bind(function() {
2479                 if (this.viewmanager && this.viewmanager.views && this.viewmanager.active_view &&
2480                     this.viewmanager.views[this.viewmanager.active_view] &&
2481                     this.viewmanager.views[this.viewmanager.active_view].controller) {
2482                     var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2483                     if (this.viewmanager.active_view === "form") {
2484                         if (!view.is_initialized.isResolved()) {
2485                             return false;
2486                         }
2487                         var res = $.when(view.do_save());
2488                         if (!res.isResolved() && !res.isRejected()) {
2489                             console.warn("Asynchronous get_value() is not supported in form view.");
2490                         }
2491                         return res;
2492                     } else if (this.viewmanager.active_view === "list") {
2493                         var res = $.when(view.ensure_saved());
2494                         if (!res.isResolved() && !res.isRejected()) {
2495                             console.warn("Asynchronous get_value() is not supported in list view.");
2496                         }
2497                         return res;
2498                     }
2499                 }
2500                 return false;
2501             }, this));
2502     },
2503     is_valid: function() {
2504         this.validate();
2505         return this._super();
2506     },
2507     validate: function() {
2508         this.invalid = false;
2509         if (!this.viewmanager.views[this.viewmanager.active_view])
2510             return;
2511         var view = this.viewmanager.views[this.viewmanager.active_view].controller;
2512         if (this.viewmanager.active_view === "form") {
2513             for (var f in view.fields) {
2514                 f = view.fields[f];
2515                 if (!f.is_valid()) {
2516                     this.invalid = true;
2517                     return;
2518                 }
2519             }
2520         }
2521     },
2522     is_dirty: function() {
2523         this.save_any_view();
2524         return this._super();
2525     },
2526     update_dom: function() {
2527         this._super.apply(this, arguments);
2528         var self = this;
2529         if (this.previous_readonly !== this.readonly) {
2530             this.previous_readonly = this.readonly;
2531             if (this.viewmanager) {
2532                 this.is_loaded = this.is_loaded.pipe(function() {
2533                     self.viewmanager.stop();
2534                     return $.when(self.load_views()).then(function() {
2535                         self.reload_current_view();
2536                     });
2537                 });
2538             }
2539         }
2540     }
2541 });
2542
2543 openerp.web.form.One2ManyDataSet = openerp.web.BufferedDataSet.extend({
2544     get_context: function() {
2545         this.context = this.o2m.build_context([this.o2m.name]);
2546         return this.context;
2547     }
2548 });
2549
2550 openerp.web.form.One2ManyListView = openerp.web.ListView.extend({
2551     _template: 'One2Many.listview',
2552     do_add_record: function () {
2553         if (this.options.editable) {
2554             this._super.apply(this, arguments);
2555         } else {
2556             var self = this;
2557             var pop = new openerp.web.form.SelectCreatePopup(this);
2558             pop.on_default_get.add(self.dataset.on_default_get);
2559             pop.select_element(
2560                 self.o2m.field.relation,
2561                 {
2562                     title: _t("Create: ") + self.name,
2563                     initial_view: "form",
2564                     alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2565                     create_function: function(data, callback, error_callback) {
2566                         return self.o2m.dataset.create(data).then(function(r) {
2567                             self.o2m.dataset.set_ids(self.o2m.dataset.ids.concat([r.result]));
2568                             self.o2m.dataset.on_change();
2569                         }).then(callback, error_callback);
2570                     },
2571                     read_function: function() {
2572                         return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2573                     },
2574                     parent_view: self.o2m.view,
2575                     child_name: self.o2m.name,
2576                     form_view_options: {'not_interactible_on_create':true}
2577                 },
2578                 self.o2m.build_domain(),
2579                 self.o2m.build_context()
2580             );
2581             pop.on_select_elements.add_last(function() {
2582                 self.o2m.reload_current_view();
2583             });
2584         }
2585     },
2586     do_activate_record: function(index, id) {
2587         var self = this;
2588         var pop = new openerp.web.form.FormOpenPopup(self.o2m.view);
2589         pop.show_element(self.o2m.field.relation, id, self.o2m.build_context(), {
2590             title: _t("Open: ") + self.name,
2591             auto_write: false,
2592             alternative_form_view: self.o2m.field.views ? self.o2m.field.views["form"] : undefined,
2593             parent_view: self.o2m.view,
2594             child_name: self.o2m.name,
2595             read_function: function() {
2596                 return self.o2m.dataset.read_ids.apply(self.o2m.dataset, arguments);
2597             },
2598             form_view_options: {'not_interactible_on_create':true},
2599             readonly: self.o2m.is_readonly()
2600         });
2601         pop.on_write.add(function(id, data) {
2602             self.o2m.dataset.write(id, data, {}, function(r) {
2603                 self.o2m.reload_current_view();
2604             });
2605         });
2606     },
2607     do_button_action: function (name, id, callback) {
2608         var self = this;
2609         var def = $.Deferred().then(callback).then(function() {self.o2m.view.reload();});
2610         return this._super(name, id, _.bind(def.resolve, def));
2611     }
2612 });
2613
2614 openerp.web.form.One2ManyFormView = openerp.web.FormView.extend({
2615     form_template: 'One2Many.formview',
2616     on_loaded: function(data) {
2617         this._super(data);
2618         var self = this;
2619         this.$form_header.find('button.oe_form_button_create').click(function() {
2620             self.do_save().then(self.on_button_new);
2621         });
2622     },
2623     do_notify_change: function() {
2624         if (this.dataset.parent_view) {
2625             this.dataset.parent_view.do_notify_change();
2626         } else {
2627             this._super.apply(this, arguments);
2628         }
2629     }
2630 });
2631
2632 openerp.web.form.FieldMany2Many = openerp.web.form.Field.extend({
2633     template: 'FieldMany2Many',
2634     multi_selection: false,
2635     init: function(view, node) {
2636         this._super(view, node);
2637         this.list_id = _.uniqueId("many2many");
2638         this.is_loaded = $.Deferred();
2639         this.initial_is_loaded = this.is_loaded;
2640         this.is_setted = $.Deferred();
2641     },
2642     start: function() {
2643         this._super.apply(this, arguments);
2644
2645         var self = this;
2646
2647         this.dataset = new openerp.web.form.Many2ManyDataSet(this, this.field.relation);
2648         this.dataset.m2m = this;
2649         this.dataset.on_unlink.add_last(function(ids) {
2650             self.on_ui_change();
2651         });
2652         
2653         this.is_setted.then(function() {
2654             self.load_view();
2655         });
2656     },
2657     set_value: function(value) {
2658         value = value || [];
2659         if (value.length >= 1 && value[0] instanceof Array) {
2660             value = value[0][2];
2661         }
2662         this._super(value);
2663         this.dataset.set_ids(value);
2664         var self = this;
2665         self.reload_content();
2666         this.is_setted.resolve();
2667     },
2668     get_value: function() {
2669         return [commands.replace_with(this.dataset.ids)];
2670     },
2671     validate: function() {
2672         this.invalid = false;
2673     },
2674     is_readonly: function() {
2675         return this.readonly || this.force_readonly;
2676     },
2677     load_view: function() {
2678         var self = this;
2679         this.list_view = new openerp.web.form.Many2ManyListView(this, this.dataset, false, {
2680                     'addable': self.is_readonly() ? null : _t("Add"),
2681                     'deletable': self.is_readonly() ? false : true,
2682                     'selectable': self.multi_selection,
2683                     'isClarkGable': self.is_readonly() ? false : true
2684             });
2685         var embedded = (this.field.views || {}).tree;
2686         if (embedded) {
2687             this.list_view.set_embedded_view(embedded);
2688         }
2689         this.list_view.m2m_field = this;
2690         var loaded = $.Deferred();
2691         this.list_view.on_loaded.add_last(function() {
2692             self.initial_is_loaded.resolve();
2693             loaded.resolve();
2694         });
2695         $.async_when().then(function () {
2696             self.list_view.appendTo($("#" + self.list_id));
2697         });
2698         return loaded;
2699     },
2700     reload_content: function() {
2701         var self = this;
2702         this.is_loaded = this.is_loaded.pipe(function() {
2703             return self.list_view.reload_content();
2704         });
2705     },
2706     update_dom: function() {
2707         this._super.apply(this, arguments);
2708         var self = this;
2709         if (this.previous_readonly !== this.readonly) {
2710             this.previous_readonly = this.readonly;
2711             if (this.list_view) {
2712                 this.is_loaded = this.is_loaded.pipe(function() {
2713                     self.list_view.stop();
2714                     return $.when(self.load_view()).then(function() {
2715                         self.reload_content();
2716                     });
2717                 });
2718             }
2719         }
2720     }
2721 });
2722
2723 openerp.web.form.Many2ManyDataSet = openerp.web.DataSetStatic.extend({
2724     get_context: function() {
2725         this.context = this.m2m.build_context();
2726         return this.context;
2727     }
2728 });
2729
2730 /**
2731  * @class
2732  * @extends openerp.web.ListView
2733  */
2734 openerp.web.form.Many2ManyListView = openerp.web.ListView.extend(/** @lends openerp.web.form.Many2ManyListView# */{
2735     do_add_record: function () {
2736         var pop = new openerp.web.form.SelectCreatePopup(this);
2737         pop.select_element(
2738             this.model,
2739             {
2740                 title: _t("Add: ") + this.name
2741             },
2742             new openerp.web.CompoundDomain(this.m2m_field.build_domain(), ["!", ["id", "in", this.m2m_field.dataset.ids]]),
2743             this.m2m_field.build_context()
2744         );
2745         var self = this;
2746         pop.on_select_elements.add(function(element_ids) {
2747             _.each(element_ids, function(element_id) {
2748                 if(! _.detect(self.dataset.ids, function(x) {return x == element_id;})) {
2749                     self.dataset.set_ids([].concat(self.dataset.ids, [element_id]));
2750                     self.m2m_field.on_ui_change();
2751                     self.reload_content();
2752                 }
2753             });
2754         });
2755     },
2756     do_activate_record: function(index, id) {
2757         var self = this;
2758         var pop = new openerp.web.form.FormOpenPopup(this);
2759         pop.show_element(this.dataset.model, id, this.m2m_field.build_context(), {
2760             title: _t("Open: ") + this.name,
2761             readonly: this.widget_parent.is_readonly()
2762         });
2763         pop.on_write_completed.add_last(function() {
2764             self.reload_content();
2765         });
2766     }
2767 });
2768
2769 /**
2770  * @class
2771  * @extends openerp.web.OldWidget
2772  */
2773 openerp.web.form.SelectCreatePopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.SelectCreatePopup# */{
2774     template: "SelectCreatePopup",
2775     /**
2776      * options:
2777      * - initial_ids
2778      * - initial_view: form or search (default search)
2779      * - disable_multiple_selection
2780      * - alternative_form_view
2781      * - create_function (defaults to a naive saving behavior)
2782      * - parent_view
2783      * - child_name
2784      * - form_view_options
2785      * - list_view_options
2786      * - read_function
2787      */
2788     select_element: function(model, options, domain, context) {
2789         var self = this;
2790         this.model = model;
2791         this.domain = domain || [];
2792         this.context = context || {};
2793         this.options = _.defaults(options || {}, {"initial_view": "search", "create_function": function() {
2794             return self.create_row.apply(self, arguments);
2795         }, read_function: null});
2796         this.initial_ids = this.options.initial_ids;
2797         this.created_elements = [];
2798         this.render_element();
2799         openerp.web.form.dialog(this.$element, {
2800             close: function() {
2801                 self.check_exit();
2802             },
2803             title: options.title || ""
2804         });
2805         this.start();
2806     },
2807     start: function() {
2808         this._super();
2809         var self = this;
2810         this.dataset = new openerp.web.ProxyDataSet(this, this.model,
2811             this.context);
2812         this.dataset.create_function = function() {
2813             return self.options.create_function.apply(null, arguments).then(function(r) {
2814                 self.created_elements.push(r.result);
2815             });
2816         };
2817         this.dataset.write_function = function() {
2818             return self.write_row.apply(self, arguments);
2819         };
2820         this.dataset.read_function = this.options.read_function;
2821         this.dataset.parent_view = this.options.parent_view;
2822         this.dataset.child_name = this.options.child_name;
2823         this.dataset.on_default_get.add(this.on_default_get);
2824         if (this.options.initial_view == "search") {
2825             self.rpc('/web/session/eval_domain_and_context', {
2826                 domains: [],
2827                 contexts: [this.context]
2828             }, function (results) {
2829                 var search_defaults = {};
2830                 _.each(results.context, function (value, key) {
2831                     var match = /^search_default_(.*)$/.exec(key);
2832                     if (match) {
2833                         search_defaults[match[1]] = value;
2834                     }
2835                 });
2836                 self.setup_search_view(search_defaults);
2837             });
2838         } else { // "form"
2839             this.new_object();
2840         }
2841     },
2842     stop: function () {
2843         this.$element.dialog('close');
2844         this._super();
2845     },
2846     setup_search_view: function(search_defaults) {
2847         var self = this;
2848         if (this.searchview) {
2849             this.searchview.stop();
2850         }
2851         this.searchview = new openerp.web.SearchView(this,
2852                 this.dataset, false,  search_defaults);
2853         this.searchview.on_search.add(function(domains, contexts, groupbys) {
2854             if (self.initial_ids) {
2855                 self.do_search(domains.concat([[["id", "in", self.initial_ids]], self.domain]),
2856                     contexts, groupbys);
2857                 self.initial_ids = undefined;
2858             } else {
2859                 self.do_search(domains.concat([self.domain]), contexts.concat(self.context), groupbys);
2860             }
2861         });
2862         this.searchview.on_loaded.add_last(function () {
2863             self.view_list = new openerp.web.form.SelectCreateListView(self,
2864                     self.dataset, false,
2865                     _.extend({'deletable': false,
2866                         'selectable': !self.options.disable_multiple_selection
2867                     }, self.options.list_view_options || {}));
2868             self.view_list.popup = self;
2869             self.view_list.appendTo($("#" + self.element_id + "_view_list")).pipe(function() {
2870                 self.view_list.do_show();
2871             }).pipe(function() {
2872                 self.searchview.do_search();
2873             });
2874             self.view_list.on_loaded.add_last(function() {
2875                 var $buttons = self.view_list.$element.find(".oe-actions");
2876                 $buttons.prepend(QWeb.render("SelectCreatePopup.search.buttons"));
2877                 var $cbutton = $buttons.find(".oe_selectcreatepopup-search-close");
2878                 $cbutton.click(function() {
2879                     self.stop();
2880                 });
2881                 var $sbutton = $buttons.find(".oe_selectcreatepopup-search-select");
2882                 if(self.options.disable_multiple_selection) {
2883                     $sbutton.hide();
2884                 }
2885                 $sbutton.click(function() {
2886                     self.on_select_elements(self.selected_ids);
2887                     self.stop();
2888                 });
2889             });
2890         });
2891         this.searchview.appendTo($("#" + this.element_id + "_search"));
2892     },
2893     do_search: function(domains, contexts, groupbys) {
2894         var self = this;
2895         this.rpc('/web/session/eval_domain_and_context', {
2896             domains: domains || [],
2897             contexts: contexts || [],
2898             group_by_seq: groupbys || []
2899         }, function (results) {
2900             self.view_list.do_search(results.domain, results.context, results.group_by);
2901         });
2902     },
2903     create_row: function() {
2904         var self = this;
2905         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2906         wdataset.parent_view = this.options.parent_view;
2907         wdataset.child_name = this.options.child_name;
2908         return wdataset.create.apply(wdataset, arguments);
2909     },
2910     write_row: function() {
2911         var self = this;
2912         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
2913         wdataset.parent_view = this.options.parent_view;
2914         wdataset.child_name = this.options.child_name;
2915         return wdataset.write.apply(wdataset, arguments);
2916     },
2917     on_select_elements: function(element_ids) {
2918     },
2919     on_click_element: function(ids) {
2920         this.selected_ids = ids || [];
2921         if(this.selected_ids.length > 0) {
2922             this.$element.find(".oe_selectcreatepopup-search-select").removeAttr('disabled');
2923         } else {
2924             this.$element.find(".oe_selectcreatepopup-search-select").attr('disabled', "disabled");
2925         }
2926     },
2927     new_object: function() {
2928         var self = this;
2929         if (this.searchview) {
2930             this.searchview.hide();
2931         }
2932         if (this.view_list) {
2933             this.view_list.$element.hide();
2934         }
2935         this.dataset.index = null;
2936         this.view_form = new openerp.web.FormView(this, this.dataset, false, self.options.form_view_options);
2937         if (this.options.alternative_form_view) {
2938             this.view_form.set_embedded_view(this.options.alternative_form_view);
2939         }
2940         this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
2941         this.view_form.on_loaded.add_last(function() {
2942             var $buttons = self.view_form.$element.find(".oe_form_buttons");
2943             $buttons.html(QWeb.render("SelectCreatePopup.form.buttons", {widget:self}));
2944             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save-new");
2945             $nbutton.click(function() {
2946                 $.when(self.view_form.do_save()).then(function() {
2947                     self.view_form.reload_mutex.exec(function() {
2948                         self.view_form.on_button_new();
2949                     });
2950                 });
2951             });
2952             var $nbutton = $buttons.find(".oe_selectcreatepopup-form-save");
2953             $nbutton.click(function() {
2954                 $.when(self.view_form.do_save()).then(function() {
2955                     self.view_form.reload_mutex.exec(function() {
2956                         self.check_exit();
2957                     });
2958                 });
2959             });
2960             var $cbutton = $buttons.find(".oe_selectcreatepopup-form-close");
2961             $cbutton.click(function() {
2962                 self.check_exit();
2963             });
2964         });
2965         this.view_form.do_show();
2966     },
2967     check_exit: function() {
2968         if (this.created_elements.length > 0) {
2969             this.on_select_elements(this.created_elements);
2970         }
2971         this.stop();
2972     },
2973     on_default_get: function(res) {}
2974 });
2975
2976 openerp.web.form.SelectCreateListView = openerp.web.ListView.extend({
2977     do_add_record: function () {
2978         this.popup.new_object();
2979     },
2980     select_record: function(index) {
2981         this.popup.on_select_elements([this.dataset.ids[index]]);
2982         this.popup.stop();
2983     },
2984     do_select: function(ids, records) {
2985         this._super(ids, records);
2986         this.popup.on_click_element(ids);
2987     }
2988 });
2989
2990 /**
2991  * @class
2992  * @extends openerp.web.OldWidget
2993  */
2994 openerp.web.form.FormOpenPopup = openerp.web.OldWidget.extend(/** @lends openerp.web.form.FormOpenPopup# */{
2995     template: "FormOpenPopup",
2996     /**
2997      * options:
2998      * - alternative_form_view
2999      * - auto_write (default true)
3000      * - read_function
3001      * - parent_view
3002      * - child_name
3003      * - form_view_options
3004      * - readonly
3005      */
3006     show_element: function(model, row_id, context, options) {
3007         this.model = model;
3008         this.row_id = row_id;
3009         this.context = context || {};
3010         this.options = _.defaults(options || {}, {"auto_write": true});
3011         this.render_element();
3012         this.$element.dialog({
3013             title: options.title || '',
3014             modal: true,
3015             width: 960,
3016             height: 600
3017         });
3018         this.start();
3019     },
3020     start: function() {
3021         this._super();
3022         this.dataset = new openerp.web.form.FormOpenDataset(this, this.model, this.context);
3023         this.dataset.fop = this;
3024         this.dataset.ids = [this.row_id];
3025         this.dataset.index = 0;
3026         this.dataset.parent_view = this.options.parent_view;
3027         this.dataset.child_name = this.options.child_name;
3028         this.setup_form_view();
3029     },
3030     on_write: function(id, data) {
3031         if (!this.options.auto_write)
3032             return;
3033         var self = this;
3034         var wdataset = new openerp.web.DataSetSearch(this, this.model, this.context, this.domain);
3035         wdataset.parent_view = this.options.parent_view;
3036         wdataset.child_name = this.options.child_name;
3037         wdataset.write(id, data, {}, function(r) {
3038             self.on_write_completed();
3039         });
3040     },
3041     on_write_completed: function() {},
3042     setup_form_view: function() {
3043         var self = this;
3044         var FormClass = this.options.readonly
3045                 ? openerp.web.views.get_object('page')
3046                 : openerp.web.views.get_object('form');
3047         this.view_form = new FormClass(this, this.dataset, false, self.options.form_view_options);
3048         if (this.options.alternative_form_view) {
3049             this.view_form.set_embedded_view(this.options.alternative_form_view);
3050         }
3051         this.view_form.appendTo(this.$element.find("#" + this.element_id + "_view_form"));
3052         this.view_form.on_loaded.add_last(function() {
3053             var $buttons = self.view_form.$element.find(".oe_form_buttons");
3054             $buttons.html(QWeb.render("FormOpenPopup.form.buttons"));
3055             var $nbutton = $buttons.find(".oe_formopenpopup-form-save");
3056             $nbutton.click(function() {
3057                 self.view_form.do_save().then(function() {
3058                     self.stop();
3059                 });
3060             });
3061             var $cbutton = $buttons.find(".oe_formopenpopup-form-close");
3062             $cbutton.click(function() {
3063                 self.stop();
3064             });
3065             if (self.options.readonly) {
3066                 $nbutton.hide();
3067                 $cbutton.text(_t("Close"));
3068             }
3069             self.view_form.do_show();
3070         });
3071         this.dataset.on_write.add(this.on_write);
3072     }
3073 });
3074
3075 openerp.web.form.FormOpenDataset = openerp.web.ProxyDataSet.extend({
3076     read_ids: function() {
3077         if (this.fop.options.read_function) {
3078             return this.fop.options.read_function.apply(null, arguments);
3079         } else {
3080             return this._super.apply(this, arguments);
3081         }
3082     }
3083 });
3084
3085 openerp.web.form.FieldReference = openerp.web.form.Field.extend({
3086     template: 'FieldReference',
3087     init: function(view, node) {
3088         this._super(view, node);
3089         this.fields_view = {
3090             fields: {
3091                 selection: {
3092                     selection: view.fields_view.fields[this.name].selection
3093                 },
3094                 m2o: {
3095                     relation: null
3096                 }
3097             }
3098         };
3099         this.get_fields_values = view.get_fields_values;
3100         this.get_selected_ids = view.get_selected_ids;
3101         this.do_onchange = this.on_form_changed = this.do_notify_change = this.on_nop;
3102         this.dataset = this.view.dataset;
3103         this.widgets_counter = 0;
3104         this.view_id = 'reference_' + _.uniqueId();
3105         this.widgets = {};
3106         this.fields = {};
3107         this.fields_order = [];
3108         this.selection = new openerp.web.form.FieldSelection(this, { attrs: {
3109             name: 'selection',
3110             widget: 'selection'
3111         }});
3112         this.reference_ready = true;
3113         this.selection.on_value_changed.add_last(this.on_selection_changed);
3114         this.m2o = new openerp.web.form.FieldMany2One(this, { attrs: {
3115             name: 'm2o',
3116             widget: 'many2one'
3117         }});
3118         this.m2o.on_ui_change.add_last(this.on_ui_change);
3119     },
3120     on_nop: function() {
3121     },
3122     on_selection_changed: function() {
3123         if (this.reference_ready) {
3124             var sel = this.selection.get_value();
3125             this.m2o.field.relation = sel;
3126             this.m2o.set_value(null);
3127             this.m2o.$element.toggle(sel !== false);
3128         }
3129     },
3130     start: function() {
3131         this._super();
3132         this.selection.start();
3133         this.m2o.start();
3134     },
3135     is_valid: function() {
3136         return this.required === false || typeof(this.get_value()) === 'string';
3137     },
3138     is_dirty: function() {
3139         return this.selection.is_dirty() || this.m2o.is_dirty();
3140     },
3141     set_value: function(value) {
3142         this._super(value);
3143         this.reference_ready = false;
3144         var vals = [], sel_val, m2o_val;
3145         if (typeof(value) === 'string') {
3146             vals = value.split(',');
3147         }
3148         sel_val = vals[0] || false;
3149         m2o_val = vals[1] ? parseInt(vals[1], 10) : false;
3150         this.selection.set_value(sel_val);
3151         this.m2o.field.relation = sel_val;
3152         this.m2o.set_value(m2o_val);
3153         this.m2o.$element.toggle(sel_val !== false);
3154         this.reference_ready = true;
3155     },
3156     get_value: function() {
3157         var model = this.selection.get_value(),
3158             id = this.m2o.get_value();
3159         if (typeof(model) === 'string' && typeof(id) === 'number') {
3160             return model + ',' + id;
3161         } else {
3162             return false;
3163         }
3164     }
3165 });
3166
3167 openerp.web.form.FieldBinary = openerp.web.form.Field.extend({
3168     init: function(view, node) {
3169         this._super(view, node);
3170         this.iframe = this.element_id + '_iframe';
3171         this.binary_value = false;
3172     },
3173     start: function() {
3174         this._super.apply(this, arguments);
3175         this.$element.find('input.oe-binary-file').change(this.on_file_change);
3176         this.$element.find('button.oe-binary-file-save').click(this.on_save_as);
3177         this.$element.find('.oe-binary-file-clear').click(this.on_clear);
3178     },
3179     human_filesize : function(size) {
3180         var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3181         var i = 0;
3182         while (size >= 1024) {
3183             size /= 1024;
3184             ++i;
3185         }
3186         return size.toFixed(2) + ' ' + units[i];
3187     },
3188     on_file_change: function(e) {
3189         // TODO: on modern browsers, we could directly read the file locally on client ready to be used on image cropper
3190         // http://www.html5rocks.com/tutorials/file/dndfiles/
3191         // http://deepliquid.com/projects/Jcrop/demos.php?demo=handler
3192         window[this.iframe] = this.on_file_uploaded;
3193         if ($(e.target).val() != '') {
3194             this.$element.find('form.oe-binary-form input[name=session_id]').val(this.session.session_id);
3195             this.$element.find('form.oe-binary-form').submit();
3196             this.$element.find('.oe-binary-progress').show();
3197             this.$element.find('.oe-binary').hide();
3198         }
3199     },
3200     on_file_uploaded: function(size, name, content_type, file_base64) {
3201         delete(window[this.iframe]);
3202         if (size === false) {
3203             this.do_warn("File Upload", "There was a problem while uploading your file");
3204             // TODO: use openerp web crashmanager
3205             console.warn("Error while uploading file : ", name);
3206         } else {
3207             this.on_file_uploaded_and_valid.apply(this, arguments);
3208             this.on_ui_change();
3209         }
3210         this.$element.find('.oe-binary-progress').hide();
3211         this.$element.find('.oe-binary').show();
3212     },
3213     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3214     },
3215     on_save_as: function() {
3216         $.blockUI();
3217         this.session.get_file({
3218             url: '/web/binary/saveas_ajax',
3219             data: {data: JSON.stringify({
3220                 model: this.view.dataset.model,
3221                 id: (this.view.datarecord.id || ''),
3222                 field: this.name,
3223                 filename_field: (this.node.attrs.filename || ''),
3224                 context: this.view.dataset.get_context()
3225             })},
3226             complete: $.unblockUI,
3227             error: openerp.webclient.crashmanager.on_rpc_error
3228         });
3229     },
3230     on_clear: function() {
3231         if (this.value !== false) {
3232             this.value = false;
3233             this.binary_value = false;
3234             this.on_ui_change();
3235         }
3236         return false;
3237     }
3238 });
3239
3240 openerp.web.form.FieldBinaryFile = openerp.web.form.FieldBinary.extend({
3241     template: 'FieldBinaryFile',
3242     update_dom: function() {
3243         this._super.apply(this, arguments);
3244         this.$element.find('.oe-binary-file-set, .oe-binary-file-clear').toggle(!this.readonly);
3245         this.$element.find('input[type=text]').prop('readonly', this.readonly);
3246     },
3247     set_value: function(value) {
3248         this._super.apply(this, arguments);
3249         var show_value;
3250         if (this.node.attrs.filename) {
3251             show_value = this.view.datarecord[this.node.attrs.filename] || '';
3252         } else {
3253             show_value = (value != null && value !== false) ? value : '';
3254         }
3255         this.$element.find('input').eq(0).val(show_value);
3256     },
3257     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3258         this.value = file_base64;
3259         this.binary_value = true;
3260         var show_value = name + " (" + this.human_filesize(size) + ")";
3261         this.$element.find('input').eq(0).val(show_value);
3262         this.set_filename(name);
3263     },
3264     set_filename: function(value) {
3265         var filename = this.node.attrs.filename;
3266         if (this.view.fields[filename]) {
3267             this.view.fields[filename].set_value(value);
3268             this.view.fields[filename].on_ui_change();
3269         }
3270     },
3271     on_clear: function() {
3272         this._super.apply(this, arguments);
3273         this.$element.find('input').eq(0).val('');
3274         this.set_filename('');
3275     }
3276 });
3277
3278 openerp.web.form.FieldBinaryImage = openerp.web.form.FieldBinary.extend({
3279     template: 'FieldBinaryImage',
3280     start: function() {
3281         this._super.apply(this, arguments);
3282         this.$image = this.$element.find('img.oe-binary-image');
3283     },
3284     update_dom: function() {
3285         this._super.apply(this, arguments);
3286         this.$element.find('.oe-binary').toggle(!this.readonly);
3287     },
3288     set_value: function(value) {
3289         this._super.apply(this, arguments);
3290         this.set_image_maxwidth();
3291         var url = '/web/binary/image?session_id=' + this.session.session_id + '&model=' +
3292             this.view.dataset.model +'&id=' + (this.view.datarecord.id || '') + '&field=' + this.name + '&t=' + (new Date().getTime());
3293         this.$image.attr('src', url);
3294     },
3295     set_image_maxwidth: function() {
3296         this.$image.css('max-width', this.$element.width());
3297     },
3298     on_file_change: function() {
3299         this.set_image_maxwidth();
3300         this._super.apply(this, arguments);
3301     },
3302     on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
3303         this.value = file_base64;
3304         this.binary_value = true;
3305         this.$image.attr('src', 'data:' + (content_type || 'image/png') + ';base64,' + file_base64);
3306     },
3307     on_clear: function() {
3308         this._super.apply(this, arguments);
3309         this.$image.attr('src', '/web/static/src/img/placeholder.png');
3310     }
3311 });
3312
3313 openerp.web.form.FieldStatus = openerp.web.form.Field.extend({
3314     template: "EmptyComponent",
3315     start: function() {
3316         this._super();
3317         this.selected_value = null;
3318
3319         this.render_list();
3320     },
3321     set_value: function(value) {
3322         this._super(value);
3323         this.selected_value = value;
3324
3325         this.render_list();
3326     },
3327     render_list: function() {
3328         var self = this;
3329         var shown = _.map(((this.node.attrs || {}).statusbar_visible || "").split(","),
3330             function(x) { return _.str.trim(x); });
3331         shown = _.select(shown, function(x) { return x.length > 0; });
3332
3333         if (shown.length == 0) {
3334             this.to_show = this.field.selection;
3335         } else {
3336             this.to_show = _.select(this.field.selection, function(x) {
3337                 return _.indexOf(shown, x[0]) !== -1 || x[0] === self.selected_value;
3338             });
3339         }
3340
3341         var content = openerp.web.qweb.render("FieldStatus.content", {widget: this, _:_});
3342         this.$element.html(content);
3343
3344         var colors = JSON.parse((this.node.attrs || {}).statusbar_colors || "{}");
3345         var color = colors[this.selected_value];
3346         if (color) {
3347             var elem = this.$element.find("li.oe-arrow-list-selected span");
3348             elem.css("border-color", color);
3349             if (this.check_white(color))
3350                 elem.css("color", "white");
3351             elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-before");
3352             elem.css("border-left-color", "rgba(0,0,0,0)");
3353             elem = this.$element.find("li.oe-arrow-list-selected .oe-arrow-list-after");
3354             elem.css("border-color", "rgba(0,0,0,0)");
3355             elem.css("border-left-color", color);
3356         }
3357     },
3358     check_white: function(color) {
3359         var div = $("<div></div>");
3360         div.css("display", "none");
3361         div.css("color", color);
3362         div.appendTo($("body"));
3363         var ncolor = div.css("color");
3364         div.remove();
3365         var res = /^\s*rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)\s*$/.exec(ncolor);
3366         if (!res) {
3367             return false;
3368         }
3369         var comps = [parseInt(res[1]), parseInt(res[2]), parseInt(res[3])];
3370         var lum = comps[0] * 0.3 + comps[1] * 0.59 + comps[1] * 0.11;
3371         if (lum < 128) {
3372             return true;
3373         }
3374         return false;
3375     }
3376 });
3377
3378 openerp.web.form.WidgetHtml = openerp.web.form.Widget.extend({
3379     render: function () {
3380         var $root = $('<div class="oe_form_html_view">');
3381         this.render_children(this, $root);
3382         return $root.html();
3383     },
3384     render_children: function (object, $into) {
3385         var self = this,
3386             fields = this.view.fields_view.fields;
3387         _(object.children).each(function (child) {
3388             if (typeof child === 'string') {
3389                 $into.text(child);
3390             } else if (child.tag === 'field') {
3391                 $into.append(
3392                     new (self.view.registry.get_object('frame'))(
3393                         self.view, {tag: 'ueule', attrs: {}, children: [child] })
3394                             .render());
3395             } else {
3396                 var $child = $(document.createElement(child.tag))
3397                         .attr(child.attrs)
3398                         .appendTo($into);
3399                 self.render_children(child, $child);
3400             }
3401         });
3402     }
3403 });
3404
3405
3406 /**
3407  * Registry of form widgets, called by :js:`openerp.web.FormView`
3408  */
3409 openerp.web.form.widgets = new openerp.web.Registry({
3410     'frame' : 'openerp.web.form.WidgetFrame',
3411     'group' : 'openerp.web.form.WidgetGroup',
3412     'notebook' : 'openerp.web.form.WidgetNotebook',
3413     'notebookpage' : 'openerp.web.form.WidgetNotebookPage',
3414     'separator' : 'openerp.web.form.WidgetSeparator',
3415     'label' : 'openerp.web.form.WidgetLabel',
3416     'button' : 'openerp.web.form.WidgetButton',
3417     'char' : 'openerp.web.form.FieldChar',
3418     'id' : 'openerp.web.form.FieldID',
3419     'email' : 'openerp.web.form.FieldEmail',
3420     'url' : 'openerp.web.form.FieldUrl',
3421     'text' : 'openerp.web.form.FieldText',
3422     'date' : 'openerp.web.form.FieldDate',
3423     'datetime' : 'openerp.web.form.FieldDatetime',
3424     'selection' : 'openerp.web.form.FieldSelection',
3425     'many2one' : 'openerp.web.form.FieldMany2One',
3426     'many2many' : 'openerp.web.form.FieldMany2Many',
3427     'one2many' : 'openerp.web.form.FieldOne2Many',
3428     'one2many_list' : 'openerp.web.form.FieldOne2Many',
3429     'reference' : 'openerp.web.form.FieldReference',
3430     'boolean' : 'openerp.web.form.FieldBoolean',
3431     'float' : 'openerp.web.form.FieldFloat',
3432     'integer': 'openerp.web.form.FieldFloat',
3433     'float_time': 'openerp.web.form.FieldFloat',
3434     'progressbar': 'openerp.web.form.FieldProgressBar',
3435     'image': 'openerp.web.form.FieldBinaryImage',
3436     'binary': 'openerp.web.form.FieldBinaryFile',
3437     'statusbar': 'openerp.web.form.FieldStatus',
3438     'html': 'openerp.web.form.WidgetHtml'
3439 });
3440
3441
3442 };
3443
3444 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: